从源文件中读取并将内容拆分为另外两个单独的文件

时间:2015-03-01 15:28:46

标签: java file-io java-io

我的目标是希望从名为“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();
}



}
}

2 个答案:

答案 0 :(得分: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();
        }

答案 1 :(得分:0)

创建两个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.