我需要程序读入带有多行随机字符串的.txt文件,并将每个偶数行放在一个.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);
}
}
}
答案 0 :(得分:4)
您应关闭PrintWriter以将输出刷新到文件。完成文件操作后,您需要执行以下操作:
file1.close();
file2.close();
注意:最好在PrintWriter
块之外声明try
个对象,以便您可以使用finally
关闭作者。