如何打印到文件?

时间:2012-04-20 16:44:00

标签: java

我正在完成一项任务,遇到了一些障碍。

我的程序将输出打印到屏幕上(不是我现在还需要它),但只打印文件的第一个条目。下面是代码片段。该文件似乎正在读取输入文件中的数据,但循环不会输出到第一个条目之后的文件。

Scanner in = new Scanner(System.in);    //Scanner object to read input from the file
System.out.println("Enter filename to read ");  //file name prompt  
String inputFileName = in.nextLine();                //line input reads next line

/*
 * TODO 2) Use an unbuffered file input stream to open listings.txt file
 * and read in property listings.
 */
Scanner reader = null;
try {
    reader = new Scanner(new File(inputFileName));
} catch (FileNotFoundException e) {

    System.out.println("Try Again");   //error window if name is null
    JOptionPane.showMessageDialog(null, "You must enter a filename", "File input error", JOptionPane.ERROR_MESSAGE);
    return;

}

PrintWriter out = new PrintWriter("agentreport.txt"); //This method prints out the file readfile.txt a word at a time
while (reader.hasNextLine()) {                      //It needs to output to the text file. Currently a file is created, but it is empty?
    Scanner s2 = new Scanner(reader.next());

    @SuppressWarnings("unused")
    boolean b;
    while (b = s2.hasNext()) {
        String output = s2.next();
        String output2 = output.toUpperCase(); //converts output to upper case
        System.out.println(output2);
        out.print(output2);  //only printing the first entry to the agentsreport.txt file. Not stepping thru the file for some reason? 
   }

4 个答案:

答案 0 :(得分:3)

即使您使用自动刷新(在这种情况下不是这种情况),PrintWriter对象也会在其内部缓冲区中输出任何内容,除非您执行以下两项操作之一:

1)使用println()printf()format()方法

2)每次打印时调用flush()方法,这样就可以写出内部缓冲区中的所有数据。

注意:print()方法导致PrintWriter对象为其flush()缓冲区。

在致电flush()

后尝试添加对print()的来电

split()

的示例
PrintWriter out = new PrintWriter("agentreport.txt"); 
while (reader.hasNextLine()) {                    
    String words = reader.nextLine().split();

    @SuppressWarnings("unused")
    boolean b;
    for(String word : words) {
        String output = word ;
        String output2 = output.toUpperCase(); //converts output to upper case
        System.out.println(output2);
        out.print(output2);  
   }

答案 1 :(得分:0)

out.println(output2);

http://docs.oracle.com/javase/6/docs/api/java/io/PrintWriter.html

我也使用除了“out”之外的var,因为当导入system.out以使用短代码'out.println()'时,这可能会导致变量混乱

编辑:好点@Hunter McMillen,改为println,因为追加是CharSequence。

答案 2 :(得分:0)

立即跳出来的一件事是你没有正确处理你的资源。

每次使用IO资源(如读取器/数据库连接等)时,都应该使用finally块关闭它,使用这种模式:

Reader reader = /* construct it however */
try {
    /* do something with the reader */
}
finally {
    reader.close();
}

如果你不这样做,不能保证读者实际上会被关闭,你的应用程序将泄漏文件描述符/连接池连接等,直到最终它将无法获取任何更多,你的应用程序崩溃。 (这不会总是会产生致命的后果,但它是一种直截了当的模式,你应该每次都使用它,直到它变成自动的。)

在这种情况下,您并未完全关闭作家 ,这意味着无法保证它实际上其输出刷新到文件中。完全按照Writer界面来编写所有内容或什么都没有 - 没有刷新,你无法保证。请注意,关闭编写器将自动调用flush,这样一旦你完成它就是最好的选择。

因此,代码的后半部分应如下所示:

PrintWriter out = new PrintWriter("agentreport.txt");
try {
    // Existing code here
}
finally {
    // This closes the file and frees the descriptor, but also flushes the buffers
    out.close();
}

另外,你如何处理阅读和写作可以抛出的IOException?你是否抓住它们并吞咽它们?如果是这样,你的代码可能会抛出一个异常,告诉你为什么它不能写,你只是忽略它然后看起来很困惑。

不要过分强调,错误处理可能是良好软件开发的最重要部分。编写一切都很好的软件并不难;最具挑战性的部分是当硬盘驱动器空间不足或网络暂时停机等情况时处理好事情。

在这种情况下,最实用的方法是让异常被抛出main方法的顶部。在这种情况下,您的应用程序将“崩溃”,并且您将在控制台上收到堆栈跟踪+错误消息,这将使其立即明确出现问题,并让您非常了解它是什么。

答案 3 :(得分:0)

try ( 
   Scanner reader = new Scanner(new File(inputFileName));
   PrintWriter writer = new PrintWriter(new FileOutputStream("agentreport.txt"), true);
) {

   while (reader.hasNextLine()) {                     
      String output = reader.nextLine().toUpperCase();
      System.out.println(output);
      writer.println(output); 
   }
} catch (FileNotFoundException e) {

   System.out.println("Try Again");   //error window if name is null
   JOptionPane.showMessageDialog(null, "You must enter a filename", "File input error", JOptionPane.ERROR_MESSAGE);

}
相关问题