【问题标题】:Processing fields from an existing text file in Java在 Java 中处理现有文本文件中的字段
【发布时间】:2018-07-11 09:00:10
【问题描述】:

我对 Java 比较陌生,我被分配了一些听起来像这样的小作业:

来自具有 x 行文本且具有以下模型的文本文件:

整数 ||一个字符串 ||另一个字符串,定义一个类,将 .txt 文件中的这些字段反序列化并将它们转换为模型集,我需要处理这些字段,然后将它们序列化回 .txt 文件。

我仍然无法从一个已经存在的大约 100 行的文本文件中理解如何做到这一点。

谁能给我一个提示或我可能错过的文章?

【问题讨论】:

  • 我不认为这与java序列化有关。您需要查看FileBufferedReader api 以进行文件读取。这个想法更多的是逐行读取文件并处理该行。
  • 如果您不知道在哪一行会遇到文本或数字 - 我认为这是一个涉及使用正则表达式的问题。它不是与序列化相关的问题。当你想传输一个对象时,就实现了序列化。
  • @Bogdan 请分享您的文件以及您迄今为止所做的工作以找到所需的解决方案
  • 这里没有serialization。不清楚你在问什么。
  • 逐一读取行,检索整数和两个字符串,使用它们来实例化表示项目的类(您将希望它有一个接受整数和两个字符串的构造函数) .塔达姆,你完了。正如其他人所说,反序列化一词的使用有点令人困惑,因为它暗示文件的内容是先前存在的 java 对象序列化的结果。也就是说,它也不是不正确的,它的常见用法只是暗示一种不属于你的情况。

标签: java java-io


【解决方案1】:

假设在你的 txt 文件中你是这样的:

1||a||b
2||text||more text

你会这样读:

public class FileReader {

    public static void main(String[] args) {

        String csvFile = "/path/to/input/file.txt";
        BufferedReader br = null;
        String line = "";
        String cvsSplitBy = "||";
        List<Model> modelList = new ArrayList<Model>();

        try {

            br = new BufferedReader(new FileReader(csvFile));
            while ((line = br.readLine()) != null) {

                // use comma as separator
                String[] line = line.split(cvsSplitBy);

               Model model = new Model(Integer.valueOf(line[0]), line[1], line[2]);
               modelList.add(model)

            }

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (br != null) {
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }

    class Model {
        private int intValue;
        private String stringValue1;
        private String stringValue2;

        public Model(int intValue,
        String stringValue1,
        String stringValue2) {
            this.intValue = intValue;
            this.stringValue1 = stringValue1;
            this.stringValue2 = stringValue2;
        }

        //getters
    }

}

此代码基于this tutorial

一旦有了模型列表,就很容易生成字符串列表,然后将其写入文件。

【讨论】:

    猜你喜欢
    • 2017-04-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-05
    • 2012-05-22
    • 2010-10-21
    • 1970-01-01
    • 2011-09-10
    相关资源
    最近更新 更多