有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

在Java中处理现有文本文件中的字段

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

来自一个文本文件,该文件具有多个x行文本,且具有以下模型:

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

我仍然无法从一个已有的文本文件中理解如何做到这一点,该文件有大约100行

有人能给我一个提示或一篇我可能错过的文章吗


共 (1) 个答案

  1. # 1 楼答案

    假设在yur 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

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