Java程序,它获取一个文件并将逐行分隔成另外两个文件 - 家庭作业



我需要程序读取具有多行随机字符串的.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);
        }
    } 
}

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

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

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

最新更新