Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java - Only read first line of a file

Tags:

java

I only want to read the first line of a text file and put that first line in a string array.

This is what I have but its reading the whole file.

ex text in myTextFile:

Header1,Header2,Header3,Header4,Header5
1,2,3,4,5
6,7,8,9,10





String line= System.getProperty("line.separator");
String strArray[] = new String[5];


String text = null;
BufferedReader brTest = new BufferedReader(new FileReader(myTextFile));
    text = brTest .readLine();
        while (text != line) {
            System.out.println("text = " + text );
             strArray= text.split(",");
         }
like image 395
Doc Holiday Avatar asked Jul 10 '14 03:07

Doc Holiday


People also ask

How to read line by line of a file in Java?

We can use java. io. BufferedReader readLine() method to read file line by line to String. This method returns null when end of file is reached.

How do you read the second line of a text file in Java?

//read the file, line by line from txt File file = new File("train/traindata. txt"); FileReader fr = new FileReader(file); BufferedReader br = new BufferedReader(fr); String line; line = br. readLine(); while(line != null) { lines = line.

How do you read the last line of a file in Java?

This snippet should work for you: BufferedReader input = new BufferedReader(new FileReader(fileName)); String last, line; while ((line = input. readLine()) != null) { last = line; } //do something with last!

How do I remove the first line of a string in Java?

Assuming there's a new line at the end of the string that you would like to remove, you can do this: s = s. substring(s. indexOf('\n')+1);


3 Answers

With Java 8 and java.nio you can also do the following:

String myTextFile = "path/to/your/file.txt";
Path myPath = Paths.get(myTextFile);
String[] strArray = Files.lines(myPath)
    .map(s -> s.split(","))
    .findFirst()
    .get();

If TAsks assumption is correct, you can realize that with an additional

.filter(s -> !s.equals(""))
like image 194
feob Avatar answered Sep 18 '22 09:09

feob


use BufferedReader.readLine() to get the first line.

BufferedReader brTest = new BufferedReader(new FileReader(myTextFile));
    text = brTest .readLine();
   System.out.println("Firstline is : " + text);
like image 21
bumbumpaw Avatar answered Oct 16 '22 11:10

bumbumpaw


If I understand you, then

String text = brTest.readLine();
// Stop. text is the first line.
System.out.println(text);
String[] strArray = text.split(",");
System.out.println(Arrays.toString(strArray));
like image 17
Elliott Frisch Avatar answered Oct 16 '22 12:10

Elliott Frisch