简体   繁体   English

如何从文本区域逐行读取

[英]How to read line by line from a text area

I have figured out how to read in line by line and display the contents of a text document line by line into a jtextarea and I have figured out how to write out line by line from an array of strings to the text document. 我已经弄清楚如何逐行阅读并逐行显示文本文档的内容到jtextarea我已经想出如何逐行写出字符串数组到文本文档。 I am just having a hard time getting each line from the textarea, as soon as I can get each line into an array i am good to go. 我只是很难从textarea获得每一行,只要我能将每一行都放到一个数组中我就好了。 Below is the code I am going to use to write each line to the file... 下面是我将用于将每行写入文件的代码...

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 C

What you get from TextArea is just a String. 你从TextArea得到的只是一个字符串。 Split it at newline and you've got your String[]. 将它拆分为换行符,你就得到了你的String []。

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

I tried to use the methods provided by the JTextArea class to answer this question. 我试图使用JTextArea类提供的方法来回答这个问题。

Hope this helps someone since I couldn't find the answer when I googled it. 希望这有助于某人,因为当我用Google搜索时我找不到答案。 All that you need to do now is implement the method processLine(String lineStr) 您现在需要做的就是实现方法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
        }

See the definition of the class here JTextArea Java 1.7 在这里查看类的定义JTextArea Java 1.7

Happy coding!!! 快乐的编码!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM