0

我需要程序读取具有多行随机字符串的 .txt 文件,并将每个偶数行放入一个 .txt 文件中,并将每个奇数行放入另一个中。它没有给我任何错误,但是当我检查它们时文件是空白的。谢谢你的帮助 :)

import java.util.*;
import java.io.*;
public class SplitFile
{
    public static void main(String[] args)
    {
        try 
        {
            // Open Scanner for file named args[0]
            Scanner scan = new Scanner(new File(args[0]));
            // Open a PrintWriter for file named args[1]
            PrintWriter file1 = new PrintWriter(new File(args[1]));
            // Open a PrintWriter for file named args[2]
            PrintWriter file2 = new PrintWriter(new File(args[2]));
            while (scan.hasNextLine())
            {
                // Read a line from scan
                // Write that line to file1
                file1.println(scan.nextLine() + ", ");

                if (scan.hasNextLine()) 
                {
                    // Read a line from scan
                    // Write that line to file2
                    file2.println(scan.nextLine() + ", ");
                }
            }
        }
        // Catch the IOException 
        catch (IOException ex)
        {
            System.out.println("Error: No Input Given");
            System.exit(0);
        }
    } 
}
4

1 回答 1

4

您应该关闭 PrintWriter 以将输出刷新到文件中。完成文件操作后,您需要执行以下操作:

file1.close();
file2.close();

注意:最好PrintWriter在块外声明对象,try以便您可以使用finally关闭编写器。

于 2013-11-01T13:13:25.577 回答