如何从文本区逐行读取

9

我已经找到了逐行读取文本文档并将其内容逐行显示到jtextarea中的方法,并且我已经找到了从字符串数组逐行写出到文本文档的方法。我只是很难从textarea中获取每一行,一旦我能够将每一行放入数组中,我就可以继续进行了。下面是我将用于将每一行写入文件的代码...

public class FileWrite {

    public static void FileClear(String FileName) throws IOException{
        FileWriter fstream = new FileWriter(FileName,true);
        BufferedWriter out = new BufferedWriter(fstream);
        out.write("");
    }

    public static void FileWriters(String FileName, String Content) throws IOException
    {   
        FileWriter fstream = new FileWriter(FileName,true);
        BufferedWriter out = new BufferedWriter(fstream);
        out.append(Content);
        out.newLine();

    }
}

Thanks

c


可能是重复问题: https://dev59.com/OHRB5IYBdhLWcg3w9L3n - erikxiv
2个回答

28

TextArea 获取的是一个字符串。在换行符处拆分它,你就得到了一个字符串数组。

for (String line : textArea.getText().split("\\n")) doStuffWithLine(line);

数组索引是从零开始的。[0-9]。 - Marko Topolnik
我本来想输入0,哈哈出错了。我有一个问题,当我运行for循环时,在最后一行它会给我一个数组越界错误,那是因为它没有下一行可以分割吗?我该怎么解决这个问题?谢谢。 - Charlie
好的,那就按照我给你展示的方式进行修改吧。你的示例有问题,因为你允许i等于行数,如果这对你很重要的话。如果你使用我展示的方法,就根本不需要担心索引的问题了。 - Marko Topolnik
啊,等等,我只是匆匆看了一眼重新编辑的版本,没有注意到它是一个for循环!谢谢! - Charlie
谢谢,太棒了!我甚至不知道用for循环可以做到这一点! - Charlie
显示剩余2条评论

1

我尝试使用JTextArea类提供的方法来回答这个问题。

希望这能帮助到一些人,因为当我谷歌搜索时找不到答案。现在你所需要做的就是实现processLine(String lineStr) 方法。

        int lines = textArea.getLineCount();

        try{// Traverse the text in the JTextArea line by line
            for(int i = 0; i < lines; i ++){
                int start = textArea.getLineStartOffset(i);
                int end = texttArea.getLineEndOffset(i);
                // Implement method processLine
                processLine(textArea.getText(start, end-start));

            }
        }catch(BadLocationException e){
            // Handle exception as you see fit
        }

在这里查看该类的定义 JTextArea Java 1.7

编程愉快!!!


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接