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.
Related
This question already has answers here:
Why does my ArrayList contain N copies of the last item added to the list?
(5 answers)
Closed 2 years ago.
So I wanted this to be my last resort because I did enough progress with doing the main code and I was only to come here if nothing else worked.
String line = "";
try
{
BufferedReader br = new BufferedReader (new FileReader("league.txt"));
FootballClub club = new FootballClub();
while ( ( line = br.readLine() ) != null )
{
String[] FC = line.split(",");
club.setName(FC[0]);
club.setLocation(FC[1]);
club.setMatchesPlayed(Integer.parseInt(FC[2]));
club.setWins(Integer.parseInt(FC[3]));
club.setDraws(Integer.parseInt(FC[4]));
club.setLosses(Integer.parseInt(FC[5]));
club.setGoalsScored(Integer.parseInt(FC[6]));
club.setGoalsAgainst(Integer.parseInt(FC[7]));
club.setGoalDifference(Integer.parseInt(FC[8]));
club.setPoints(Integer.parseInt(FC[9]));
league.add(club);
}
br.close();
}
catch (FileNotFoundException e) { }
catch (IOException e){ }
This is my code from reading from a text file into array. The text file is as follows:
Chelsea,London,0,0,0,0,0,0,0,0
WestHam,London,0,0,0,0,0,0,0,0
The problem is that when I test the program, two clubs get added to the array however the values for the first line get overridden by the second line. I have been trying to get one line added first then the second until there is no line but I seem to be lucking out. I have been looking everywhere to try and fix it but no luck and it does seem like an easy fix but I'm burned out and can't find it. Any pointers and suggestions would be appreciated.
You need to create a new instance of the class on each iteration, otherwise you keep setting properties on the same object, so only the last line will be stored.
while ((line = br.readLine()) != null){
String[] FC = line.split(",");
FootballClub club = new FootballClub();
//...
}
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("&")) {
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.
This question already has answers here:
Inserting text into an existing file via Java
(8 answers)
Closed 9 years ago.
I want to insert a line into a specific location of a .txt file. Now the only way I know is to read out the whole file out as an array, put the given line in the correct place and then write the whole thing back. Is there an easier way to achieve this using Java? My intention is to reduce the file access as much as possible.
Is there an easier way to achieve this using Java?
With Java 7, unless your insertion point is towards the end of a huge file, I would simply do:
List<String> lines = Files.readAllLines(path, StandardCharsets.UTF_8);
lines.add(position, extraLine);
Files.write(path, lines, StandardCharsets.UTF_8);
Try to read and write at the same time by using BufferedReader.
The Idea is to read line and immediately write it to other file.
BufferedReader rd = null;
BufferedWriter wt = null;
try {
rd = new BufferedReader(
new InputStreamReader(
new FileInputStream("/yourfile.txt"), "UTF-8")
);
wt = new BufferedWriter(
new OutputStreamWriter(
new FileOutputStream(
"/newfile" + ".txt"), "UTF-8")
);
int count = 0;
for (String line; (line = reader.readLine()) != null;) {
count++
if (count == 6) {
// add your line
// wt.write(newline);
}
wt.write(line);
wt.newLine();
}
} finally {
close(wt);
close(rd);
}
RandomAccessFile do not solve this problem. It was discussed in this post. You should rewrite file anyway.
You can only read and write it with some buffer, alter it and immidiate write to new to save your program memory.
This question already has answers here:
Android read text raw resource file
(14 answers)
Closed 3 years ago.
I'm currently trying to read a file from (res/raw) by using an InputStream that I dimension like such:
InputStream mStream = this.getResources().openRawResource(R.raw.my_text_file_utf_8);
I then put that into this method to return the values:
public List<String> getWords(InputStream aFile) {
List<String> contents = new ArrayList<String>();
try {
BufferedReader input = new BufferedReader(new InputStreamReader(aFile));
try {
String line = new String();//not declared within while loop
while ((line = input.readLine()) != null ){
contents.add(line);
}
}
finally {
input.close();
}
}
catch (IOException ex){
ex.printStackTrace();
}
return contents;
}
My problem: It reads all the values as it should, but say if the file is 104 lines long, it will actually return a value of something like 134 total lines with the remaining 30 lines being full of null??
Have checked: Already using UTF-8 format, and double checked that there are literally no blank lines within the document itself...
I thought the way the while loop was written that it couldn't record a line=null value to contents List? Am I missing something here?
Thanks for any constructive information! I'm pretty sure I'm overlooking some simple factoid here though...
Why dont you create HTML for your information and then parse it.