JavaIO : Using scanner and printWriter to copy the contents of a text file and put them in another text file

标签 java file io java.util.scanner printwriter

好吧,我正在开发一个非常小的程序,旨在获取文本文件 test.txt 的内容,并将它们放入另一个空文件 testCopied.txt 中。诀窍是我想使用 Scanner 和 printWriter 因为我想更好地理解它们。

这是我的代码:

import java.io.*;
import java.util.*;

public class CopyA
{
   public static void main(String [] args)
   {
      String Input_filename = args[0];
      String Output_filename = args[1];
      char r = args[2].charAt(0);

      try
      {
         Scanner sc = new Scanner(new File(Input_filename));
         FileWriter fw = new FileWriter(Output_filename);
         PrintWriter printer = new PrintWriter(fw);

         while(sc.hasNextLine())
         {
            String s = sc.nextLine();
            printer.write(s);
         }
         sc.close();               
      }
      catch(IOException ioe)
      {
         System.out.println(ioe);
      }
   }
}

这可以编译,但是当我查看 testCopied.txt 时,它仍然是空白,并且没有将 test.txt 的内容传输到其中。我究竟做错了什么? Java IO 让我很困惑,所以我试图更好地掌握它。非常感谢任何帮助!

最佳答案

您错过了需要添加的 PrintWriter 对象的 flush() 和 close()

然后使用 System.getProperty("line.separator") 来使用行分隔符,同时将每一行写入第二个文件。

您可以引用以下代码:

PrintWriter printer = null;
Scanner sc = null;
try
  {
     String lineSeparator = System.getProperty("line.separator");

     sc = new Scanner(new File(Input_filename));
     FileWriter fw = new FileWriter(Output_filename);
     printer = new PrintWriter(fw);

     while(sc.hasNextLine())
     {
        String s = sc.nextLine()+lineSeparator; //Add line separator
        printer.write(s);
     }
  }
  catch(IOException ioe)
  {
     System.out.println(ioe);
  } finally {
    if(sc != null) {
       sc.close();  
    }
    if(printer != null) {
      printer.flush();
      printer.close();
     }
 }

此外,请确保始终关闭 finally block 中的资源(您在代码中错过了 Scanner 对象)。

关于JavaIO : Using scanner and printWriter to copy the contents of a text file and put them in another text file,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40598402/

相关文章:

Java:如何通过从mongodb(远程服务器)读取数据来加速JTree重建?

c++ - 是否有用于写入 STDOUT 或文件的 C++ 习惯用法?

flutter - 尝试在 Flutter 中创建一个新的文本文件

java - 如何在 Java 应用程序中播放 ALAW 文件?

php - 读取没有最后 x 字节的文件

c++ - C/C++。输入行数字

java - 使用 Lucene 作为存储

java - log4J 与 java applet 和 java 插件2

java - 按日期对 RecyclerView 进行排序

Java 正则表达式不适用于文件验证