【问题标题】:Java: Splitting a file into a string for each line?Java:将文件拆分为每行的字符串?
【发布时间】:2017-11-19 22:50:51
【问题描述】:

您好,我正在努力让我的代码读取每一行并将其保存到每个单独行的字符串中。我的代码在下面加载文本文件,但我似乎无法拆分它,我可以得到第一行拆分,就是这样。我在 Java 方面并不出色,但我正在尝试加载一个有 4 行的文本文件,我需要将该文件中的代码拆分为不同的字符串。我可以得到它来获取第一行代码,但仅此而已。

    Load.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {

            JFileChooser fileChooser = new JFileChooser();

            int returnValue = fileChooser.showOpenDialog(null);

            if (returnValue == JFileChooser.APPROVE_OPTION) {


                File file = fileChooser.getSelectedFile();

                try {

                    BufferedReader reader = new BufferedReader(new FileReader(file));


                    String nextLine = reader.readLine();


                    if ( nextLine != null && nextLine.startsWith("Title:")) { 

                        title = nextLine.substring(6);

                        panel.showText(title);
                        nextLine = reader.readLine();
                    }


                    reader.close();
                } catch (IOException e1) {

                    System.err.println("Error while reading the file");
                } 
            }


        }
    }); 

【问题讨论】:

    标签: java split line bufferedreader


    【解决方案1】:

    我认为下面可能有用https://kodejava.org/how-do-i-read-text-file-content-line-by-line-using-commons-io/

    这表明来自 apache commons 的 FileUtils。从上面的网站复制。

     File file = new File("sample.txt");
    
            try {
                List<String> contents = FileUtils.readLines(file);
    
                // Iterate the result to print each line of the file.
                for (String line : contents) {
                    System.out.println(line);
                }
            }
    

    【讨论】:

    • 请在此处添加该链接中的相关详细信息,因为如果该链接的内容稍后发生更改,您在此处的答案可能会变差。
    【解决方案2】:
    while(nextLine != null){
         if ( nextLine != null && nextLine.startsWith("Title:")) { 
            title = nextLine.substring(6);
            panel.showText(title);
            nextLine = reader.readLine();
         }
    }
    reader.close();
    

    应该这样做

    【讨论】:

    • 你为什么要检查两次 nextLine != null
    • 强调在哪里添加一个while循环而不是代码本身,如果我真的被它困扰,我会把它溢出到一个它可能应该是的方法中
    猜你喜欢
    • 1970-01-01
    • 2018-04-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-21
    • 2015-01-31
    相关资源
    最近更新 更多