【问题标题】:Making Java I / O and change the file to split in java在java中进行Java I/O和更改文件拆分
【发布时间】:2014-07-15 02:13:06
【问题描述】:

我正在制作一个使用 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();
    }
}
}

我想要的是从已经输入的数据中生成如上的输出

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

谢谢:)

【问题讨论】:

  • 抱歉,您还有什么问题?具体来说,您的代码有什么问题?
  • ... 而不是直接使用 FileOutputStream 写入,为什么不使用适合使用字符串的 Stream,例如使用 PrintStream 包装 FileOutputStream?
  • 哦,对不起,也许我的英语不好,我只想在输入文件中使用 BufferedReader 更改它,当文件已经存在时。我想更改拆分删除“| "用(“\ \ |”),如果是转换文件将被保存回Berhasil.txt 名称。谢谢
  • @MadBoy 为什么需要阅读 rtp 扩展?
  • 我有一个格式为 (.RPT) 的文件和我放在上面的内容。

标签: java io split bufferedreader


【解决方案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();
    }
}
}

【讨论】:

  • 哦,对不起,我还是看不懂Java I/O。你能解释一下吗?我应该在我的源代码中更改什么。谢谢
  • 我试过了,确实很顺利,但是正则表达式“|”中有一点字符会被缩小成一个个字母,而不是限制,所以我再次用“\ \ |”更改,非常感谢您的帮助,应用到框架中会很好。 :)
猜你喜欢
  • 1970-01-01
  • 2017-02-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-07-05
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多