Android: Write text to txt

早过忘川 提交于 2019-12-19 09:14:24

问题


With the following code, I try to write to my sdcard:

public void writedata(String data) {
          //BufferedWriter out = null;

          System.out.println(data);
          try{

              FileOutputStream out = new FileOutputStream(new File("/sdcard/tsxt.txt"));
              out.write(data.getBytes());
              out.close();  

                } catch (Exception e) { //fehlende Permission oder sd an pc gemountet}
                    System.out.println("CCCCCCCCCCCCCCCCCCCCCCCALSKDJLAK");
                }

          }

The permission in the Manifest:

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>  

But now, when I open the file, nothing is in there. Where´s the problem? I´m sure data has some value.

EDIT:

I get this message in the LogCat:

02-06 01:59:51.676: W/System.err(1197): java.io.FileNotFoundException: /storage/sdcard0/sdcard/tsxt.txt: open failed: ENOENT (No such file or directory)

I tried to create the file on the sdcard but still the same error. Is there a code that the File is created if it doesn´t exists?


回答1:


Try with this code:

File sdCard = Environment.getExternalStorageDirectory();
File dir = new File (sdCard.getAbsolutePath() + "/dir");

File file = new File(dir, "tsxt.txt");

FileOutputStream f = new FileOutputStream(file);

So the path to the file is not correct. You should remove directory name:

File dir = new File (sdCard.getAbsolutePath() + "/");



回答2:


Try this:

BufferedWriter out;         
try {

FileWriter fileWriter= new FileWriter(Environment.getExternalStorageDirectory().getPath()+"/tsxt.txt")

out = new BufferedWriter(fileWriter);

out.write("Your text to write");

out.close(); 

}catch (FileNotFoundException e) {
 e.printStackTrace();
}catch (IOException e) {
 e.printStackTrace();
}



回答3:


  try{
    File myFile = new File("/sdcard/tsxt.txt");
    myFile.createNewFile();
    FileOutputStream fOut = new FileOutputStream(myFile);
    OutputStreamWriter myOutWriter = new OutputStreamWriter(fOut);
    myOutWriter.append("your data here");
    myOutWriter.close();
    fOut.close();
}catch(Exception e){}



回答4:


Try this

 FileOutputStream fOut =openFileOutput(Environment.getExternalStorageDirectory().getPath()+"/tsxt.txt",MODE_WORLD_READABLE);
 OutputStreamWriter osw = new OutputStreamWriter(fOut);
//---write the string to the file---
 osw.write(str);
 osw.flush();
 osw.close();



回答5:


Before writing any file on sd card you need to check that is sdcard mounted or not, if not then just mount it and then write the file on it using external storage path.

you may use following code to check is sdcard mount or not

static public boolean hasStorage(boolean requireWriteAccess) {
    //TODO: After fix the bug,  add "if (VERBOSE)" before logging errors.
    String state = Environment.getExternalStorageState();
    Log.v(TAG, "storage state is " + state);

    if (Environment.MEDIA_MOUNTED.equals(state)) {
        if (requireWriteAccess) {
            boolean writable = checkFsWritable();
            Log.v(TAG, "storage writable is " + writable);
            return writable;
        } else {
            return true;
        }
    } else if (!requireWriteAccess && Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
        return true;
    }
    return false;
}

if(hasStorage(true)){

//call here your writedata() function



}



回答6:


This Code is working perfectly..

public File getAlbumStorageDir(String albumName) {
        // Get the directory for the user's public pictures directory.
        File file = new File(Environment.getExternalStorageDirectory() + "/files", albumName);
       Log.d("File", "Bug file Created" + file.getAbsolutePath());
        return file;
    }`

To write the textfile inside sd Card(/storage/sdcard0/files/bugReport.txt)

 try{
             outputStream = new FileOutputStream(this.getAlbumStorageDir(bugReport.txt));
             outputStream.write(report.toString().getBytes());
             Log.d("File","Report Generated");
             outputStream.close();
         }
         catch(Exception e){
             e.printStackTrace();
         }


来源:https://stackoverflow.com/questions/16983506/android-write-text-to-txt

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!