简体   繁体   English

使用PrintWriter将字符串打印到文本文件,但是当我打开文本文件时,它为空

[英]Using PrintWriter to print a string to a text file, but when I open the text file it is empty

I'm using PrintWriter in Java to try to write some Strings to a text file, however when I open the text file it is empty. 我使用Java中的PrintWriter尝试将一些字符串写入文本文件,但是当我打开文本文件时,它为空。

Here is my code: 这是我的代码:

public void save(String fileName) throws FileNotFoundException{

    PrintWriter out1 = new PrintWriter("aSB.txt");
    out1.println("The Pupil's information is listed below:");
    for (Pupil pup : Pupils) {
       out1.println(pup.getFirstName() + " " + pup.getLastName());
    }
    out1.println("End");
    out1.println("The Club's information is listed below:");
    for (Club clu : Clubs) {
       out1.println(clu.getName());
    }
    out1.close();   
}

Why is the filename empty? 为什么文件名是空的?

Try to catch FileNotFoundException and see if you have error creating the file. 尝试捕获FileNotFoundException并查看是否在创建文件时出错。 Also try catching SecurityException. 也可以尝试捕获SecurityException。 If not try using FileOutputStream. 如果不是,请尝试使用FileOutputStream。 It is really easy to use it Good luck! 使用起来真的很容易祝你好运!

As Kevin said, maybe directory issues. 正如Kevin所说,也许是目录问题。 Try to specify the full path see what happens. 尝试指定完整路径,看看会发生什么。

Something like: 就像是:

PrintWriter pw = new PrintWriter("c:/asb.txt");

Alternatively, see here 另外,请看这里

quite possibly the array are empty 很有可能数组是空的

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

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