制作Java I / O并将文件更改为在java中拆分

时间:2014-07-15 02:13:06

标签: java io split bufferedreader

我正在制作一个使用java I / O的项目

我有一个包含以下数据的文件:

  

170631 | 0645 | | 002014 | 0713056699 | 000000278500   155414 | 0606 | | 002014 | 0913042385 | 000001220000   000002 | 0000 | 0000 | 00000000000 | 0000000000000000 | 000000299512

我想要的输出如下:

  

170631

     

0645

     

002014

文件,以便减少数据 这是我的源代码:

public class Tes {
public static void main(String[] args) throws IOException{
    File file;
    BufferedReader br =null;
    FileOutputStream fop = null;
    try {
        String content = "";
        String s;
        file = new File("E:/split/OUT/Berhasil.RPT");
        fop = new FileOutputStream(file);
        br = new BufferedReader(new FileReader("E:/split/11072014/01434.RPT"));
        if (!file.exists()) {
            file.createNewFile();
        }
        while ((s = br.readLine()) != null ) {
            for (String retVal : s.split("\\|")) {

                String data = content.concat(retVal);
                System.out.println(data.trim());        
                byte[] buffer = data.getBytes();
                fop.write(buffer);
                fop.flush();
                fop.close();
            }
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
}
}

我想要从输入的数据

中生成上述输出

文件输入 - >拆分 - >文件输出

谢谢:)

1 个答案:

答案 0 :(得分:1)

我想你忘了提到你面临的问题。只需查看代码,每次在编写分割线时循环时,您似乎都在关闭fop(FileOutputStream)。一旦你在while循环之外编写了所有内容,就应该关闭outputStream。

import java.io.*;

public class FileReadWrite {

public static void main(String[] args) {
    try {
        FileReader inputFileReader = new FileReader(new File("E:/split/11072014/01434.RPT"));
        FileWriter outputFileWriter = new FileWriter(new File("E:/split/11072014/Berhasil.RPT"));
        BufferedReader bufferedReader = new BufferedReader(inputFileReader);
        BufferedWriter bufferedWriter = new BufferedWriter(outputFileWriter);
        String line;
        while ((line = bufferedReader.readLine()) != null) {
            for (String splitItem : line.split("|")) {
                bufferedWriter.write(splitItem + "\n");
            }
        }
        bufferedWriter.flush();
        bufferedWriter.close();
        bufferedReader.close();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}
}