Java BufferedReader won't go to the next line - java

Sorry for the noob question, but I feel like my code is correct but I can't see why the read won't go to the next line:
This is my code so far:
BufferedReader buffer = null;
try {
FileReader file = new FileReader(filename);
buffer = new BufferedReader(file);
String line = buffer.readLine();
String[] separations = line.split(", ");
System.out.println(separations[0]);
while(line!= null) {
this.times.add(separations[0]);
Double number = Double.parseDouble(separations[1]);
allNumbers.add(number);
line = buffer.readLine();
}

The issue was not that the buffer was only reading one line but I was tokenizing the line outside of the loop, so the same information got stored for x number of lines:
Solution:
while (line != null) {
String[] separations = line.split(", "); // this should be inside the loop
if (separations.length > 1) {
this.times.add(separations[0]);
Double number = Double.parseDouble(separations[1]);
allNumbers.add(number);
}
line = buffer.readLine();
}

Related

How to read text file without the headline into ArrayList

I'm currently working on an assignment and I cannot find any clue to remove the headline from the text file and write the rest into an ArrayList. Can someone help me?
ID,Nama,GajiPokok,JmlAbsensi,JmlIzin
2,Peter,5000000,17,3
1,John,4500000,19,1
3,Linda,10000000,13,7
4,Lucy,7000000,20,0
Here is my code:
BufferedReader in = new BufferedReader(new FileReader("D:\\" + args[0] + ".txt"));
try {
String line = in.readLine();
String data[];
while (line != null){
data = line.split(",");
Staff s = new Staff(){};
s.setID(Integer.parseInt(data[0]));
s.setNama(data[1]);
s.setGajiPokok(Long.parseLong(data[2]));
s.setjmlhAbsensi(Integer.parseInt(data[3]));
s.setjmlhIzin(Integer.parseInt(data[4]));
s.getID();
s.getNama();
s.getGajiPokok();
s.getjmlhAbsensi();
s.getjmlhIzin();
list_Staff.addAll(Arrays.asList(s));
line = in.readLine();
}
in.close();
} catch (IOException e){e.printStackTrace();}
If you want to ignore first line while reading the CSV file then you can simple skip processing of 1st line by calling in.readLine(); twice at the start as shown in below example:
BufferedReader in = new BufferedReader(new FileReader("D:\\" + args[0] + ".txt"));
String line = in.readLine();
line = in.readLine(); //skip fist line and read second line
String data[];
while (line != null){
data = line.split(",");
Staff s = new Staff(){};
s.setID(Integer.parseInt(data[0]));
s.setNama(data[1]);
s.setGajiPokok(Long.parseLong(data[2]));
s.setjmlhAbsensi(Integer.parseInt(data[3]));
s.setjmlhIzin(Integer.parseInt(data[4]));
s.getID();
s.getNama();
s.getGajiPokok();
s.getjmlhAbsensi();
s.getjmlhIzin();
list_Staff.addAll(Arrays.asList(s));
line = in.readLine();
}
Using skip() method of JAVA 8 Streams:
try(BufferedReader in = new BufferedReader(new FileReader("D:\\" + args[0] + ".txt"))) {
Stream<String> lines = in.lines();
List<Staff> staff = lines.skip(1).map(line -> {
Staff s = new Staff();
String data[] = line.split(",");
s.setID(Integer.parseInt(data[0]));
s.setNama(data[1]);
s.setGajiPokok(Long.parseLong(data[2]));
s.setJmlhAbsensi(Integer.parseInt(data[3]));
s.setJmlhIzin(Integer.parseInt(data[4]));
return s;
}).collect(Collectors.toList());
System.out.println(staff);
}
You can declare the following line twice or initialize integer variable and skip the loop if its zero.
String line = in.readLine();
This solution works.
private void readTextFile(String fileName) throws FileNotFoundException {
BufferedReader in = new BufferedReader(new FileReader(fileName));
Stream<String> stream = in.lines();
List<String> answer = stream.collect(Collectors.toList());
// For Pre-Java8
/*for (int i = 1; i < answer.size(); i++) {
System.out.println(answer.get(i));
}*/
// Split afterwards.
Stream<String> ans = answer.stream().filter(p -> !p.equals(answer.get(0)));
ans.forEach(x -> System.out.println(x));
}

How to read a file from a specific line to another specific line?

So I'm trying to make a file reader to read from x line to y line but when i execute the program it reads all the lines of the file and not the lines that should have started and ended, For example if i'm looking an ID in the file it should print de ID, The name of the holder(the next line of the ID Line), and his/her address(Next line of the name Line), but instead of print just that it prints all the ID'S, Names and Addresses of everyone in the file.
System.out.println("Escriba el ID Del Cliente");
CL.setID(reader.next());
String line2;
int count = 0;
try {
BufferedReader input = new BufferedReader(new FileReader(file));
Scanner input2 = new Scanner(file);
PrintWriter output = new PrintWriter(new FileOutputStream(file, true));
LineNumberReader readers = new LineNumberReader(new InputStreamReader(new FileInputStream(file), "UTF-8"));
while((line2 = input.readLine()) != null)
{
if(line2.contains(CL.getID()))
{
while(((line2 = readers.readLine()) != null) && readers.getLineNumber() <= count + 3)
{
count++;
System.out.println(line2);
}
input.close();
input2.close();
output.close();
readers.close();
break;
}
}
}catch(IOException ex)
{
System.out.println("ERRORR!!!!!!");
}
I've modified your code because the problem was at the count++ which will eventually led to reading all the lines from your files, and at the line2 = readers.readLine() which will read from the first line of the file again ( the program works half correct because it reads only 3 lines and only if line2 contains your ID ). Now, to make your program work correctly, you need to either use the BufferedReader or the LineNumberReader.
public static void main(String[] args) {
System.out.println("Escriba el ID Del Cliente");
String line2;
File file = new File(yourpathhere);
int lineCount = 0;
try {
PrintWriter output = new PrintWriter(new FileOutputStream(file, true));
LineNumberReader readers = new LineNumberReader(new InputStreamReader(new FileInputStream(file), "UTF-8"));
while ((line2 = readers.readLine()) != null) {
lineCount++;
if (line2.contains(CL.getId())) {
while (line2 != null && readers.getLineNumber() <= lineCount + 3) {
System.out.println(line2);
line2 = readers.readLine();
}
output.close();
readers.close();
break;
}
}
} catch (IOException ex) {
System.out.println("ERRORR!!!!!!");
}
}
PS : pay attention for the getLineNumber() method because it increments the lines read until the moment you're calling it. It means that if we didn't had the lineCount and the ID we're trying to find was at the 6th line, the getLineNumber() value at the moment when line2.contains(CL.getId()) == true was 6, so the readers.getLineNumber() <= 3 will be FALSE and the program won't work correctly anymore. ( We need to keep track for the lines read until the moment we check for the id )
Assuming you have a file with 100 lines and you want to check and print out line 5 to 10 you could try this:
System.out.println("Escriba el ID Del Cliente");
CL.setID(reader.next());
String line;
int count = 0;
int xLine = 5;
int yLine = 10;
try (BufferedReader input = new BufferedReader(new FileReader(file)))
{
while((line = input.readLine()) != null)
{
if(count < xLine)
{
// skip all lines lower then start
continue;
}
else if(count >= xLine && count <= yLine && line.contains(CL.getID()))
{
// print line if line is between lines to read
// and if line contains ID
System.out.println(line);
}
else
{
// break if count is bigger then yLine
break;
}
count++;
}
}
catch(IOException ex)
{
System.out.println("ERRORR!!!!!!");
}
You read all lines till the BufferedReader reaches null. You check if the line contains your ID. Then you check if the count is between the linenumbers you want to check / print. Then you increment the count for the lines processed.
I simplified the try-catch-Block with a try-with-ressources Statement. As for now I don't see what your plans with output and scanner were, so I removed them.

How to modify my readFile function so it does not stop at first line (java)

the following code will only read the first line of a text file and it will stop there. I've been experimenting with loops but i cannot get it to successfully update the line until there are no more lines in the file. can anyone help? thanks
public void readFile(){
try {
BufferedReader in = new BufferedReader(new FileReader("test1.txt"));
words = new ArrayList<Word>();
int lineNum = 1; // we read first line in start
// delimeters of line in this example only "space"
char [] parse = {' '};
String delims = new String(parse);
String line = in.readLine();
String [] lineWords = line.split(delims);
// split the words and create word object
for (int i = 0; i < lineWords.length; i++) {
Word w = new Word(lineWords[i]);
words.add(w);
}
lineNum++; // pass the next line
line = in.readLine();
in.close();
} catch (IOException e) {
}
}
Basically, you want to keep reading until you run out of lines, at which time BufferedReader will return null
char[] parse = {' '};
String delims = new String(parse);
String line = null;
while ((line = in.readLine()) != null) {
String[] lineWords = line.split(delims);
// split the words and create word object
for (int i = 0; i < lineWords.length; i++) {
Word w = new Word(lineWords[i]);
words.add(w);
}
lineNum++; // pass the next line
}
You should be managing your resources better, if you open it, you should make all reasonable attempts to close. Currently, if your code fails for some reason, the in.close line will never be called. Also, you shouldn't ignore exceptions
Luckily, in Java 8, this is easy to manage...
try (BufferedReader in = new BufferedReader(new FileReader("test1.txt"))) {
//...
} catch (IOException e) {
e.printStackTrace();
}
Take a closer look at Basic I/O, The try-with-resources Statement and BufferedReader JavaDocs, especially BufferedReader#readLine
You may also want to take a look at LineNumberReader ;)
while((line = in.readLine()) != null){
//process line
}
This nested statement reads a line from the BufferedReader and stores it in line. At the end of the file, readLine() will return null and stop the loop.

How to Split string in java using "\n"

I am taking a command line input string like this:
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String line = br.readLine();
I want to split this string which is:
String line = "int t; //variable t
t->a = 0; //t->a does something
return 0;"
like this:
String[] arr = line.split("\n");
arr[0] = "int t; //variable t";
arr[1] = "t->a=0; //t->a does something";
arr[2] = "return 0";
but when i run my java program that split function only returns this:
arr[0] = "int t; //variable t";
it didn't returns other two strings that i mentioned above,why this is happening please explain.
The method readLine() will read the input until a new-line character is entered. That new-line character is "\n". Therefore, it won't ever read the String separated by "\n".
One solution:
You can read the lines with a while loop and store them in an ArrayList:
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
List<String> lines = new ArrayList<String>();
String line;
while ((line = br.readLine()) != null) {
lines.add(line);
}
for (String s : lines) {
System.out.println(s);
}
To stop the while you will have to press Ctrl + z (or Ctrl + d in UNIX, if I'm not wrong).
From your comment you seem to take the input like this
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
try {
String line = br.readLine();
System.out.println(line);
} catch (IOException e) {
e.printStackTrace();
}
Here the line represents already split string by \n. When you hit enter on the console, the text entered in one line gets captured into line. As per me you are reading line, only once which captures just int t;//variable t, where there is nothing to split.
This should work!Also make sure if your input contains \n
String[] arr = line.split("\r?\n")

Number of newline characters

I am designing a Utility that counts the words and Number of newline characters.
I have done count task but i dont know how to count number of new line charcaters in file.
Code:
System.out.println ("Counting Words");
InputStream stream = Run.class.getResourceAsStream("/test.txt");
InputStreamReader r = new InputStreamReader(stream);
BufferedReader br = new BufferedReader (r);
String line = br.readLine();
int count = 0;
while (line != null) {
String []parts = line.split(" ");
for( String w : parts){
count++;
}
line = br.readLine();
}
System.out.println(count);
test
This is simple file reading by Java Program
Just look inside the words:
for (char c : w.toCharArray()) {
if (c == '\n') {
numNewLineChars++;
}
}
Which goes inside the for loop you already have.
System.out.println ("Counting Words");
InputStream stream = Run.class.getResourceAsStream("/test.txt");
InputStreamReader r = new InputStreamReader(stream);
BufferedReader br = new BufferedReader (r);
String line = br.readLine();
int word_count = 0;
int line_count = 0;
while (line != null) {
String[] parts = line.split(" ");
word_count += parts.length;
line_count++;
line = br.readLine();
}
System.out.println("Word count: " + word_count + " Line count: " + line_count);
It maybe a better option here to use the LineNumberReader class for counting and reading the lines of text. Although this isn't the most efficient way for counting lines in a file (according to this question) it should suffice for most applications.
From LineNumberReader for readLine method:
Read a line of text. Whenever a line terminator is read the current line number is incremented. (A line terminator is usually a newline character '\n' or a carriage return '\r').
This means that when you call the getLineNumber method of the LineNumberReader class, it will return the current line number that has been incremented by the readLine method.
I have included comments in the code below explaining it.
System.out.println ("Counting ...");
InputStream stream = ParseTextFile.class.getResourceAsStream("/test.txt");
InputStreamReader r = new InputStreamReader(stream);
/*
* using a LineNumberReader allows you to get the current
* line number once the end of the file has been reached,
* without having to increment your original 'count' variable.
*/
LineNumberReader br = new LineNumberReader(r);
String line = br.readLine();
// use a long in case you use a large text file
long wordCount = 0;
while (line != null) {
String[] parts = line.split(" ");
wordCount+= parts.length;
line = br.readLine();
}
/* get the current line number; will be the last line
* due to the above loop going to the end of the file.
*/
int lineCount = br.getLineNumber();
System.out.println("words: " + wordCount + " lines: " + lineCount);

Categories

Resources