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(",");
}
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.
//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.
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!
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);
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(""))
use BufferedReader.readLine()
to get the first line.
BufferedReader brTest = new BufferedReader(new FileReader(myTextFile));
text = brTest .readLine();
System.out.println("Firstline is : " + text);
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));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With