简体   繁体   English

在写入文件时需要帮助

[英]Need Help In Writing To A File

i have the following class that writes to a file but is not working as i want. 我有下面的类写到文件,但不能按我想要的方式工作。 I call the write method in a while loop so that it writes a string to a new line. 我在while循环中调用write方法,以便它将字符串写入新行。 It only writes the last string. 它只写最后一个字符串。 All the previous ones are not written except the last one. 除最后一个以外,所有先前的均未写入。

Here is the class: 这是课程:

import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;

public class Writer {

 private static PrintWriter  outputStream = null;

 public Writer(String algorithmName){
  try {
   outputStream = new PrintWriter(new FileWriter(algorithmName+".txt"));
  } catch (IOException e) {
   e.printStackTrace();
  }
 }
     public  void write(String str){
        try {
                outputStream.append(str);
        }catch(Exception exc){

        } finally {
            if (outputStream != null) {
                outputStream.close();
            }
        }
    }
}

example code: 示例代码:

Writer w = new Writer("filename");
for(int = i; i < 10; i++){
w.write(i);
}

In this case i get as results: 在这种情况下,我得到的结果是:

9

instead of 代替

0
1
2
3
...
9

what am i doing wrong? 我究竟做错了什么?

thanks 谢谢

You're closing the output stream after every write operation. 您将在每次写操作后关闭输出流。 You should call it one time after having written everything. 编写完所有内容后,您应该一次调用它。

everytime you write, you are closing the stream which then forces a new file to be created that is why all that is in the file is 9. 每次编写时,您都将关闭流,然后强制创建一个新文件,这就是为什么文件中只有9个文件的原因。

Writer output = new BufferedWriter(new FileWriter(algorithmName+".txt"));
try {
  for(int = i; i < 10; i++){
      output.write( i );
  }
}
finally {
  output.close();
}

I'll be a bit off topic and recommend the Google Guava library to you, since it contains a lot of useful everyday functionality. 我会有点话题,向您推荐Google Guava库,因为它包含很多有用的日常功能。

Using it, the solution to your problem becomes almost a one-liner with: 使用它,您的问题的解决方案几乎变成了一种选择:

for(int i = 0; i < 10; ++i) {
    Files.append(String.valueOf(i) + "\n", new File("filename"), Charsets.UTF_8);
}

Edit: you shouldn't use this in large loops because the library is probably effectively opening and closing the file every single time. 编辑:您不应该在大型循环中使用它,因为该库可能每次都有效地打开和关闭文件。 Not efficient at all. 根本没有效率。

You have several bad mistakes here. 您在这里有几个严重的错误。 You have used a standard class name as your own class name; 您已经使用标准的类名作为自己的类名。 you are closing the stream after every write, as the others have noted; 正如其他人所指出的,您在每次写操作后都将关闭流; the stream is a static member when it should be an instance member; 当流应该是实例成员时,它是静态成员; and you have an empty catch block which is preventing you from seeing any errors whatsoever. 并且您有一个空的catch块,这将阻止您看到任何错误。 Never do that. 绝对不要那样做。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM