Android:写文本到txt [英] Android: Write text to txt
问题描述
使用下面的代码,我尝试写入我的SD卡:
public void writedata(String data){
// BufferedWriter out = null;
System.out.println(data);
尝试{
FileOutputStream out = new FileOutputStream(new File(/ sdcard / tsxt.txt));
out.write(data.getBytes());
out.close();
} catch(Exception e){// fehlende Permission or sd an pc gemountet}
System.out.println(CCCCCCCCCCCCCCCCCCCCCCCALSKDJLAK);
$ b $ / code
$ b $ <$> / p>
< uses-permission android:name =android.permission.WRITE_EXTERNAL_STORAGE/>
但现在,当我打开文件时,没有任何内容。问题在哪里?我确信 data
有一定的价值。
编辑:
我在LogCat中得到这个信息:
02-06 01:59: 51.676:W / System.err(1197):java.io.FileNotFoundException:/storage/sdcard0/sdcard/tsxt.txt:打开失败:ENOENT(没有这样的文件或目录)
我试图在SD卡上创建文件,但仍然出现相同的错误。是否有代码,如果它不存在的文件创建?
解决方案试试这个代码:
文件sdCard = Environment.getExternalStorageDirectory();
File dir = new File(sdCard.getAbsolutePath()+/ dir);
档案档案=新档案(dir,tsxt.txt);
FileOutputStream f = new FileOutputStream(file);
所以文件路径不正确。您应该删除目录名称:
$ b $ pre $ 文件dir = new File(sdCard.getAbsolutePath()+/);
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?
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() + "/");
这篇关于Android:写文本到txt的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!