19

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(",");
         }
Koray Tugay
  • 22,894
  • 45
  • 188
  • 319
Doc Holiday
  • 9,928
  • 32
  • 98
  • 151

8 Answers8

23

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

BufferedReader brTest = new BufferedReader(new FileReader(myTextFile));
    text = brTest .readLine();
   System.out.println("Firstline is : " + text);
bumbumpaw
  • 2,522
  • 1
  • 24
  • 54
17

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));
Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249
8

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(""))
Community
  • 1
  • 1
feob
  • 1,930
  • 5
  • 19
  • 31
  • 5
    Be careful: Files.lines does not auto close the file. – FRotthowe Sep 11 '18 at 11:41
  • 3
    will it actually load all content to memory? – Yeung Mar 02 '22 at 10:21
  • 2
    @Yeung, yes, It will load the full file as stream. From the docs: "Read all lines from a file as a Stream. Bytes from the file are decoded into characters using the UTF-8 charset." If your will work with medium-large files better use bufferedReader solution – JuniorGuy Jul 11 '22 at 09:13
4

Also, beside of all other solutions presented here, you could use guava utility class (Files), like below:

import com.google.common.io.Files;
//...

String firstLine = Files.asCharSource(myTextFile).readFirstLine();
tmucha
  • 689
  • 1
  • 4
  • 19
1

I think you are trying to get one line only if it's not empty.

You can use

 while ((text=brTest .readLine())!=null){
    if(!text.equals("")){//Ommit Empty lines
         System.out.println("text = " + text );
         strArray= text.split(",");
         System.out.println(Arrays.toString(strArray));
         break;
    }
 }
akash
  • 22,664
  • 11
  • 59
  • 87
1

I hope this will help someone

to read the first line:

public static String getFirstLine() throws IOException {
    BufferedReader br = new BufferedReader(new FileReader("C:\\testing.txt")); 

    String line = br.readLine(); 
    br.close();
    return line;
}

to read the whole text:

public static String getText() throws IOException {
    BufferedReader br = new BufferedReader(new FileReader("C:\\testing.txt")); 
    StringBuilder sb = new StringBuilder(); 
    String line = br.readLine(); 

    while (line != null) { 
        sb.append(line).append("\n"); 
        line = br.readLine(); 
    } 
    String fileAsString = sb.toString();
    br.close();
    return fileAsString;
}
Community
  • 1
  • 1
Snowbases
  • 2,316
  • 2
  • 20
  • 26
0

Use this

BuffereedReader reader = new BufferedReader(new FileReader(textFile));
StringBuilder builder = new StringBuilder();

StringBuilder sb = new StringBuilder();
String line = br.readLine();

        while (line != null) {
            sb.append(line);
         break;
        }
if(sb.toString.trim().length!=0)
System.out.println("first line"+sb.toString);
-1

You need to change the condition of your loop

  String[] nextLine;   
  while((nextLine = brTest.readLine()) != null) {
      ...
  }

ReadLine reads each line from beginning up to the occurrence of \r andor \n You can also use tokenizer to split the string

String[] test = "this is a test".split("\\s");

In addition it seems the file is of type CSV if it is please mention that in the question.

Jack
  • 6,430
  • 27
  • 80
  • 151
  • @Unihedron I changed the syntax – Jack Jul 10 '14 at 03:12
  • This is a correct, idiomatic approach to read a file, especially when filtering into a `StringBuilder`. Unfortunately it appears not to answer the question. – Unihedron Jul 10 '14 at 03:14
  • @Unihedron whats wrong with it ? it reads all lines one by one, questioner can break the loop after reading the first line. – Jack Jul 10 '14 at 03:17
  • Actually, __[empty lines are returned `""` through `.readLine()`](http://docs.oracle.com/javase/7/docs/api/java/io/BufferedReader.html#readLine())__. Only when the reader has reached end of stream, will `.readLine() != null` return false. Maybe you want `!= null && ! .equals("")`? – Unihedron Jul 10 '14 at 03:18
  • readline stop reading the line as soon as it reaches to a \n or \r, once it reaches to those put whatever it read into nextLine then you can use the nextLine string which contains a line of the file. – Jack Jul 10 '14 at 03:22
  • Empty lines in text files are essentially multiple `\n\r`s. – Unihedron Jul 10 '14 at 03:23
  • is it a CSV file ? is this your question? – Jack Jul 10 '14 at 03:24