سؤال

I have 3 text files that all contain strings from objects.

I have a GUI with a list that is populated with the contents of one text file. Im currently looking to implement something that would take the line number from the first file and pull out the strings from the same line number in other files. Can anyone recommend anything?

هل كانت مفيدة؟

المحلول

You can use:

 String[] lines = secondFileText.split("\n");

P.s.- If that doesn't work try replacing \n with \r\n.

نصائح أخرى

You can split a string into lines:

String[] lines = s.split("\r?\n");

Then you can access the line at any index:

System.out.println(lines[0]);  // The array starts at 0

Note: On Windows, the norm for ending lines is to use a carriage-return followed by a line-feed (CRLF). On Linux, the norm is just LF. The regular expression "\r?\n" caters for both cases - it matches zero or one ("?") carriage-returns ("\r") followed by a line-feed ("\n").

BufferedReader will deal well with huge files that won't fit in memory, it's pretty fast and deal with both \r and \n

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;


public class ReadByLine {

    /**
     * @param args
     * @throws FileNotFoundException 
     */
    public static void main(String[] args) throws FileNotFoundException {
        File f = new File("xyz.txt");
        int lineNumber = 666;

        BufferedReader br = new BufferedReader(new FileReader(f));
        String line = null;
        int count = -1;
        try {
            while((line = br.readLine())!=null){
                count++;
                if (count == lineNumber){
                    //get the line, do what you want
                    break;
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally{
            try {
                br.close();
            } catch (IOException e) {
                br = null;
            }
        }

        //do what you want with the line

    }

}
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top