开发者

Write to a file in java

How can I modify this run method to not only print the srting in the output window, but also write to a file for example outfile.txt in project directory. Also each string should be on a separate line in the file.

So I have already created a file in the project directory called outfile.txt

A the moment the code is print fine on window but not printing in the text file

here is the code #

public void run() throws IOException
{
    Scanner sc = new Scanner(System.in);
    boolean cont = true;
    while (cont) {
       System.out.println("Enter text");
       String s = sc.nextLine();
       if ("*".equals(s)) {
           cont = false;
       } else {
           String result = shorthand开发者_开发百科(s);
           System.out.println(result);
           PrintWriter pw = new PrintWriter("outfile.txt");
           pw.println(result);
      }
   }
}


Once you finish writing out, you need to close the open file:

pw.Close();


Just take a look at exampledot.


You should not use relative paths in java.io.File stuff. They will be relative to the current working directory which in turn depends on the way how you started the Java application. This may not be per se the project directory you expect it to be. You should always use absolute paths in java.io.File. E.g. c:/path/to/outfile.txt.

To learn where it is currently actually been written to, do:

 File file = new File("outfile.txt");
 System.out.println(file.getAbsolutePath());

Once again, never use relative paths. Always use absolute paths. Else just put it in the classpath and make use of ClassLoader#getResource() and then URL#toURI() and then new File(uri).

And indeed, close the streams. It will implicitly flush the data buffer to the resource.


You're creating a new printwriter every time. Consider making it before the loop, as such

PrintWriter pw = new...
while(cond) {
    ...
    pw.println(...);
    pw.flush(); // do this too, it does the actual writing
}
pw.close();
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜