Write a string to a file

后端 未结 4 1910

I want to write something to a file. I found this code:

private void writeToFile(String data) {
    try {
        OutputStreamWriter outputStreamWriter = new Ou         


        
4条回答
  •  旧时难觅i
    2021-01-31 18:44

    You can write complete data in logData in File

    The File will be create in Downlaods Directory

    This is only for Api 28 and lower .

    This will not work on Api 29 and higer

    @TargetApi(Build.VERSION_CODES.P)
    public static File createPrivateFile(String logData) {
        String fileName = "/Abc.txt";
        File directory = new File(Environment.getExternalStorageDirectory() + "/" + Environment.DIRECTORY_DOWNLOADS + "/");
        directory.mkdir();
        File file = new File(directory + fileName);
        FileOutputStream fos = null;
        try {
            if (file.exists()) {
                file.delete();
            }
            file = new File(getAppDir() + fileName);
            file.createNewFile();
            fos = new FileOutputStream(file);
            fos.write(logData.getBytes());
            fos.flush();
            fos.close();
            return file;
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
    

提交回复
热议问题