我正在尝试将程序的输出发送到名为results.txt的文本文件。这是我的尝试
public void writeFile(){
try{
PrintStream r = new PrintStream(new File("Results.txt"));
PrintStream console = System.out;
System.setOut(r);
} catch (FileNotFoundException e){
System.out.println("Cannot write to file");
}
但是每次我运行代码并打开文件时,文件都是空白的。这是我要输出的内容:
public void characterCount (){
int l = all.length();
int c,i;
char ch,cs;
for (cs = 'a';cs <='z';cs++){
c = 0;
for (i = 0; i < l; i++){
ch = all.charAt(i);
if (cs == ch){
c++;
}
}
if (c!=0){
//THIS LINE IS WHAT I'M TRYING TO PRINT
System.out.println("The character"+ " "+ cs + " "+ "appears --> "+" "+c+" "+ "times");
}
}
}
我在哪里出错,它会继续创建文件但不写入文件? (顺便说一句,我确实有一个主要方法)
答案 0 :(得分:1)
使用:
PrintWriter writer = new PrintWriter("Results.txt");
writer.print("something something");
别忘了添加:
writer.close();
完成后!
答案 1 :(得分:1)
您发现System.out
是IS-A PrintStream
,您可以创建一个PrintStream
,并向其传递File
以使其写入该文件。这就是多态的妙处---您的代码写到PrintStream
上,与它的类型无关:控制台,文件,甚至网络连接或压缩的网络文件。
因此,不要搞乱System.setOut
(通常是一个坏主意,因为它可能会有意想不到的副作用;仅在绝对必须(例如,在某些测试中)时才这样做),只需通过{{1 }}选择您的代码:
PrintStream
然后您可以根据需要调用方法:
public void characterCount (PrintStream writeTo) {
// (your code goes here)
writeTo.println("The character"+ " "+ cs + " "+ "appears --> "+" "+c+" "+ "times");
// (rest of your code)
}
(请注意,我声明public static void main(String[] args) throws FileNotFoundException {
new YourClass().characterCount(System.out);
new YourClass().characterCount(new PrintStream(new File("Results.txt")));
}
可能会抛出main
,因为FileNotFoundException
会抛出该错误。发生这种情况时,程序将退出并显示错误消息和堆栈跟踪。您也可以像以前在new File("...")
中一样处理它。)
答案 2 :(得分:0)
JAVADOC:“一个PrintStream向另一个输出流添加了功能,即能够方便地打印各种数据值的表示形式。”
PrintStream可用于写入OutputStream,而不是直接写入文件。因此,您可以使用PrintStream写入FileOutputStream,然后使用它来写入文件。
但是,如果您只想简单地写入文件,则可以使用Cans答案!