0

将快速调用函数“writeToFile()”将字符串写入文本文件。但我没有在文件中看到任何文本。

代码:

 public class MyClass {
        private File data_file = new File("data_from_java.txt");
        public void writeToFile(String str){
        try {
            FileOutputStream fos= new FileOutputStream(this.data_file, true);
            System.out.print(str);  // there is text shown in terminal 
            fos.write(str.getBytes());
            fos.flush();
            fos.close();   // why file donesn't have text 
        }catch(Exception ex) {
            System.out.println(ex.getMessage());
        }
    }
4

3 回答 3

0

写入原始字节可能会导致字符编码出现问题。正如乔恩斯基特所说,使用作家......

try {
    FileWriter writer = new FileWriter(data_file, true);
    writer.write(str);
} catch(IOException e) {
    // oh no!
} finally {
    writer.close();
}
于 2012-11-20T09:20:39.333 回答
0

尝试使用这段代码:

final BufferedWriter fos = new BufferedWriter(new FileWriter(data_file, true));
System.out.print(str);
fos.write(str);
fos.flush();
fos.close();

它对我有用,尽管我确实在与我预期不同的地方找到了我的文本文件。也许稍微搜索一下就可以了?

于 2012-11-20T09:23:57.980 回答
0

在你的代码fos.write(str.getBytes());中,这一行似乎导致了问题...... write() 方法将一个字节作为参数.. 你给出字节数组.. 所以将该行更改为

buf = str.getBytes();
for (int i=0; i < buf.length; i += 2) { 
f0.write(buf[i]);
}
于 2012-11-20T09:27:22.570 回答