Read text file using java , eclipse kepler [duplicate] - java

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 8 years ago.
I am novice in Java and I am currently working in Eclipse Kepler. I have a JSP page from where I am reading a text file which is continuously being written using a shell script.
<b>
<%
String filePath = "/home/default/test.txt";
BufferedReader reader = new BufferedReader(new FileReader(filePath));
StringBuilder sb = new StringBuilder();
String line;
while((line = reader.readLine()) != "Success"){
sb.append(line+"\n");
out.println(sb.toString());
}
%>
</b>
I need the logic to keep reading the log until it reads the final "Success" string and until it doesn't, it should not print any blank rows.
How to solve it?

You can achieve it this way:
while ((line = reader.readLine()) != null) {
if (line.trim().length() == 0) {
continue;
}
if (line.equals("Success")) {
break;
} else {
// perform required operation
}
}

As epoch said, "!=" is not the same as "equals()". If you are comparing Strings always use "equals()".
while(!(line = reader.readLine()).equals("Success")) {...}

Try this:
while(!(line = reader.readLine()).equals("Success")) {
if (line.trim().length() != 0) {
out.println(line+"\n");
}
}
The line is passed directly to the out stream. The use of StringBuilder is not obvious here.

Related

Strange behavior reading files in Java [duplicate]

This question already has answers here:
BufferedReader is skipping every other line when reading my file in java
(3 answers)
Closed 4 months ago.
I'm trying to read nearly 120,000 lines from a file, put the data into a new record, and add this record to a list.
My problem is that I can't load all the data getting weird behavior.
In particular, using BufferedReader a first time I can count the rows and the result is correct, but when I try with a while loop to load the data into memory I see that the loop iterates about 60,000 times and the final list with the data contains only about 5000 objects.
I've also tried using other classes for loading data, but I always get the same problem.
I am currently using java 17 with spring and javafx.
Thank you.
I am attaching the latest version of my method:
public void getFixList(FixReadyCallback callback) {
List<Fix> fixList;
int firstCount = 0;
int whileCount = 0;
try {
File file = new File("src/main/resources/fligh_data/fix.dat");
BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(file), "UTF-8"));
String currentLine = null;
while (reader.readLine() != null) {
firstCount++;
}
fixList = new ArrayList<>(firstCount);
reader.close();
reader = new BufferedReader(new InputStreamReader(new FileInputStream(file), "UTF-8"));
while ((currentLine = reader.readLine()) != null) {
whileCount++;
currentLine = reader.readLine();
if (currentLine.matches(
"[-]?[0-9]{2}\\.[0-9]{6}\\s+[-]?[0-9]{3}\\.[0-9]{6}\\s+[0-9A-Z]{2,5}")) {
String[] splitted = currentLine.split("\\s+");
String denomination = splitted[2];
double latitude = Double.parseDouble(splitted[0]);
double longitude = Double.parseDouble(splitted[1]);
Coordinates coordinates = new Coordinates(latitude, longitude);
fixList.add(new Fix(denomination, coordinates));
}
}
System.out.println("FIRST_COUNT -> " + firstCount);
System.out.println("WHILE_COUNT -> " + whileCount);
System.out.println("LIST_SIZE -> " + fixList.size());
reader.close();
callback.onReady(fixList);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
And the output of the terminal:
FIRST_COUNT -> 119724
WHILE_COUNT -> 59862
LIST_SIZE -> 5128
while ((currentLine = reader.readLine()) != null) {
whileCount++;
currentLine = reader.readLine();
...
}
This skips every other line in your file. currentLine is already the next line in the file, and then you overwrite it with the line after that. I think you only meant to read one line per loop.
It seems pretty clear that you should simply delete the last line I quoted:
while ((currentLine = reader.readLine()) != null) {
whileCount++;
...
}

Count number of lines that starts with & character in CSV file [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
BufferedReader is skipping every other line when reading my file in java
(3 answers)
Closed 2 years ago.
I am trying to make a function that will count how many lines starts with & in given file.
So far i came up with following function
public int CountNumberOfTexts(String filename) {
try{
File file = new File(filename);
if(file.exists()){
FileReader fr = new FileReader(file);
LineNumberReader lnr = new LineNumberReader(fr);
int linenumber = 0;
while (lnr.readLine() != null){
if (lnr.readLine().substring(0,1) == "&") {
linenumber++;
}
}
Log.d("Count", "NUMBER OF LINES: " + linenumber);
lnr.close();
return linenumber;
}else{
System.out.println("File does not exists: " + filename);
}
}catch(IOException e){
e.printStackTrace();
}
return 0;
}
Current Function error is: Not recognizing lines starting with & character.
You are facing two problems:
You are reading in two lines, but only evaluating every second:
while (lnr.readLine() != null){ <- first consumption
if (lnr.readLine().substring(0,1) == "&") { <- second
You are comparing strings with == operator instead of equals method. Or in your case you can even use startsWith method which is created precisely for scenarios like yours.
This will do the trick:
String line;
while ((line = lnr.readLine()) != null){
if (line.startsWith("&")) {

Problems with flush and printwriter [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 7 years ago.
I have the following code:
while (true) {
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
out = new PrintWriter(socket.getOutputStream());
String result = null;
while (result != "string") {
out.println("string one");
out.flush();
String var = null;
if ((var = in.readLine()) != null) {
var2 = function(login);
out.println(var2);
out.flush();
}
}
}
The flushing is not working correctly, mainly the first iteration of the outer while loop will print both outputs, but then after that there is an odd delay and everything is messed up ("string one" is not printing to the output).
What am I doing wrong?
You are using != tocompare String references which isn't going to do what you thinks, though it doesn't matter because you never change anyway.
Most likely you have a bug at the other end which is why readLine() blocks waiting for some text.

BufferedReader() returning empty string when there are more strings in the file?

My txt file looks like this:
data;data2;data3;data4..........up till data3146
When I open the txt file in notepad I see it in the form given above.
But when I copy paste the first few lines to another place, There is a 1 line gap b/w data1 and everything else. Because of this I am getting problems while accessing the file in Java and using the data with a bufferedreader in a loop. How can I correct this? I can't remove the empty line as it is not even visible in the original file.
You can ignore the blank line(s). Something like this -
while ((line = reader.readLine()) != null) {
if(line.trim().isEmpty()) {
continue;
}
...
you can try this way:
BufferedReader reader = new BufferedReader(new FileReader(new File("your file path")));
String str = null;
while((str = reader.readLine())!=null) {
if (str.matches("[' ']+")) {
continue;
} else {
// to do
}
}
I believe that the problem is in the line endings. Basically you can skip the empty lines:
String line;
while ((line = reader.readLine()) != null) {
if ("".equals(line.trim()) {
continue;
}
// do your stuff here
}

Skip every odd line using BufferedReader? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Reading certain lines only from input?
Is there a way I can skip every odd line from a file if I am using BufferedReader?
Just read a line and discard it:
BufferedReader bReader = new BufferedReader(new FileReader("someFileName.txt"));
String line = null;
while(true)
{
//skip the odd line
bReader.readLine();
//read an even line
line = bReader.readLine();
if(line != null)
//do stuff with even line
else
break; //end of input
}
BufferedReader br = ...;
String line;
while ((line = br.readLine()) != null) {
line = br.readLine();
//do whatever with the data
if (line == null) break;
}

Categories