【问题标题】:Read from source file and split the contents into two other separate files从源文件中读取并将内容拆分为另外两个单独的文件
【发布时间】:2015-03-01 15:28:45
【问题描述】:

我的目标是我希望从一个名为“input.txt”的文件中读取,该文件有 10 行文本,然后将 5 行从原始文件写入另外两个名为“test1.txt”的文件中和“test2.txt”。我正在使用以下代码,但它不起作用 - 请帮助我。

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


public class main {

public static void main (String args[]) throws FileNotFoundException, IOException{


BufferedReader br = new BufferedReader (new FileReader("bin/input.txt"));
File file = new File("bin/test2.txt");
BufferedWriter writer = new BufferedWriter(new FileWriter("bin/test.txt"));


Scanner sc = new Scanner (br);

int i = 0;

while (sc.hasNextLine()){

    sc.nextLine();
    i++;
    System.out.print(i);
    int n = (i+1)/2;
    System.out.print("\n"+n);

    writer.write(sc.nextLine().toString());
    writer.newLine();
    if (n==5){
        writer.close();
    }
}


if (sc != null){
    sc.close();
}



}
}

【问题讨论】:

  • 当您使用java.io 时,您应该为您使用的任何文件创建单独的输入/输出流。

标签: java file-io java-io


【解决方案1】:

这将从单个文件中读取并将内容拆分为两个文件。

        int count = 0;
        BufferedReader br = null;
        FileWriter fileWriter1 = new FileWriter("G:\\test1.txt");
        FileWriter fileWriter2 = new FileWriter("G:\\test2.txt");

        try {
            String currentLine;
            br = new BufferedReader(new FileReader("G:\\input.txt"));
            while ((currentLine = br.readLine()) != null) {
                count++;
                if (count <= 5) {
                    fileWriter1.write(currentLine + "\n");
                } else {
                    fileWriter2.write(currentLine + "\n");
                }
            }
        } finally {
            if (br != null) {
                br.close();
            }
            fileWriter1.close();
            fileWriter2.close();
        }

【讨论】:

  • 但是在输出的txt文件中,当到达结束行时,不要跳转到下一行。在此代码行中:'code' fileWriter1.write(currentLine + "\n"); '代码'
  • 第二个 txt 输出文件杂乱无章。我的输入文本是波斯语。我该如何解决?
【解决方案2】:

创建两个 BufferedWriter 而不是一个有两个文件的,然后按照以下步骤操作:

 count <- 0
 while scanner hasNextLine
 do
     string line <- scanner's next Line
     if (count > 4) {
         writer2.write line
     } else {
         writer1.write line
     }
     count <- count + 1
 done
 finally close all three resources.

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-10-07
    • 1970-01-01
    • 2019-11-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-08
    • 1970-01-01
    相关资源
    最近更新 更多