java - 从一个文本文件读取并写入两个文本文件
问题描述
我需要从一个文本文件(carsAndBikes.txt)中读取,并且在 cars.txt 或 bikes.txt carAndBikes 中的写入包含汽车和自行车的列表,每个名称的第一个字符是 C 或 B(C 代表 Car 和 B自行车)。到目前为止,我有这个,但它展示了汽车和自行车的内容。而不是分开的内容。(仅限汽车或仅限自行车)
public static void separateCarsAndBikes(String filename) throws FileNotFoundException, IOException
{
//complete the body of this method to create two text files
//cars.txt will contain only cars
//bikes.txt will contain only bikes
File fr = new File("C:\\Users\\KM\\Documents\\NetBeansProjects\\Question4\\carsAndBikes.txt");
Scanner scanFile = new Scanner(fr);
String line;
while(scanFile.hasNextLine())
{
line = scanFile.nextLine();
if(line.startsWith("C"))
{
try(PrintWriter printWriter = new PrintWriter("C:\\Users\\KM\\Documents\\NetBeansProjects\\Question4\\cars.txt"))
{
printWriter.write(line);
}
catch(Exception e)
{
System.out.println("Message" + e);
}
}
else
{
try(PrintWriter printWriter = new PrintWriter("C:\\Users\\KM\\Documents\\NetBeansProjects\\Question4\\bikes.txt"))
{
printWriter.write(line);
}
catch(Exception e)
{
System.out.println("Message" + e);
}
}
}
//close the file
scanFile.close();
}
解决方案
您正在检查输入文件名是否以 ac 开头,而不是检查读取的行是否以 c 开头。
您还应该在循环之前打开两个输出文件,并在循环之后关闭它们。
// Open input file for reading
File file = new File("C:\\Users\\KM\\Documents\\NetBeansProjects\\Question4\\carsAndBikes.txt");
BufferedReader br = new BufferedReader(new FileReader(file)));
// Open bike outputfile for writing
// Open cars outputfile for writing
// loop over input file contents
String line;
while( line = br.readLine()) != null ) {
// check the start of line for the character
if (line.startsWith("C") {
// write to cars
} else {
// write to bikes
}
}
// close all files
推荐阅读
- python - 用于功率分配的迭代算法的python结果问题
- c - 编写自定义 USB 描述符
- python - 在 python 3 中的 jupyther notebook 中运行 python 2 中的代码
- php - ACF 转发器即将发生和过去的事件
- reporting-services - RDL 或 SSRS 报告仅显示非空集或空集的值
- javascript - 在 JS 和 jQuery 不起作用的情况下添加带有引导程序的切换按钮
- javascript - 防止 inline-block 元素移出其父级
- telerik - 如何切换到模态弹出窗口并使用 Telerik 中的编码步骤识别其中的元素
- angular - angular 6材料设计手风琴openall
- docker - 在 Windows 10 上静默启动 Docker