The code below is mostly self explanatory. However, I am having trouble in two cases:
The while loop does not exit even with the command line is left blank.
If the input is test t1 the key variable is supposed to be "test" (using System.out.println(key)) does that, but, it still doesn't enter the if condition for some reason.
String[] broken_text = null; String text = "";
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
while((text = reader.readLine()) != null) {
broken_text = text.split(" ");
String first_key = broken_text[0];
if (first_key == "test") {
//some statements
}
}
I am not sure why this is happening, any help regarding the same will be much appreciated.
use equals() to check string equality.
if (first_key == "test") {
//some statements
}
should be
if (first_key.equals("test")) {
//some statements
}
your text will never be null because you declared it as
String text = "";
thus your while loop would be an infinite loop
change
String text = "";
to
String text = null;
or if you wanna leave your text="" string as empty string.
use
while(!(text = reader.readLine()).isEmpty())
The loop does not end because a blank line causes readLine() to return an empty string, not null.
The comparison fails because Strings must be compared with equals() not ==
The String text will never be null in this case. You can use:
while (!(text = reader.readLine()).isEmpty()) {
this should be your edited code:
String[] broken_text = null;
String text = "";
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
while((text = reader.readLine()) != null && !text.isEmpty()) {
broken_text = text.split(" ");
String first_key = broken_text[0];
if ( "test".equals(first_key)) {
//some statements
}
}
The reason changed (text = reader.readLine()) != null to (text = reader.readLine()) != null && !text.isEmpty() is because readLine() returns null when it encounters end-of-file as the first character, and it returns "" (empty string) when the first character is encounters is \r (carriage return), \n(line feed) , or \r\n(carriage return followed by line feed). And you must always check for null before checking for isEmpty().
On unix / Linux console end-of-file is [ctrl][d] and on DOS it is [ctrl][z]
Note: In case you want to read input from a file (where you are more likely to get an end-of-file) instead of console, then your reader will be initialised like this:
BufferedReader reader = new BufferedReader(new FileReader("d:\\a1.txt"));
(assuming your input data is in file: "d:\a1.txt".)
Related
From third party daily reports i will be getting a similar kind of csv file as shown below
07-Jan-2016
It is better to lead from behind and to put others in front, especially when you celebrate victory when nice things occur. You take the front line when there is danger. Then people will appreciate your leadership.
The main thing that you have to remember on this journey is, just be nice to everyone and always smile.
My requirement is that i need to put each paragraph (A line after space) each quote for above reference in a separate StringBuffer
My question how can i check for empty line ??
I tried with
if(line.contains(" "))
{
System.out.println("hjjjjjjjjjjjjjjjjk");
}
But the above is causing issue where ever there is a space
I am reading the csv file as shown below
String csvFile = "ip/ASRER070116.csv";
BufferedReader br = null;
String line = "";
try {
br = new BufferedReader(new FileReader(csvFile));
while ((line = br.readLine()) != null) {
if (line.startsWith(",")) {
line = line.replaceFirst(",", "");
}
System.out.println(line);
}
}
Could you please tell me how to resolve this ??
if (line != null && (line.trim().equals("") || line.trim().equals("\n"))){
System.out.println("this is empty line");
}
I would suggest you use trim() on the read line and then check if line.length == 0
You can use StringUtils.isBlank method from Apache Commons Lang
public static boolean isBlank(CharSequence cs)
Checks if a CharSequence is whitespace, empty ("") or null.
StringUtils.isBlank(null) = true
StringUtils.isBlank("") = true
StringUtils.isBlank(" ") = true
StringUtils.isBlank("bob") = false
StringUtils.isBlank(" bob ") = false
I am trying these lines:
private String line;
private final String stopChr= "#";
BufferedReader in = new BufferedReader(new InputStreamReader(server.getInputStream()));
while ((line = in.readLine()) != null) {
tcpData = tcpData + line;
if(line.equals(stopChr)) break;
}
Why is the if statement not breaking out of the loop when # is present?
Most likely the line is not exactly "#" for example it might have a space after it. I suggest you look at what the line is in your debugger or in an editor to see exactly what characters the String has.
Try printing the following to help see what the string is actually.
System.out.println(Arrays.toString(line.toCharArray());
If you have trailing spaces you can drop these with trim
if (line.trim().equals(stopChar)) break;
If the string contains other characters, as in your example input $353323058181636,EV,D,T,567888.9,+12C,FFFFE000# (from your comment on #PeterLawrey's answer), use the following instead of String.equals:
if(line.contains(stopChr)) break;
If it specifically ends with the stop character, you can alternatively use:
if(line.endsWith(stopChr)) break;
The following code is working :
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String line = "";
String data = "";
while ((line = br.readLine()) != null) {
data += line;
if (line.contains("#"))
break;
}
Also, instead of contains() you can use endsWith() to check for end of file.
You make take help.
for getting everything before the #
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String line = "";
String data = "";
while (true)
{
line = br.readLine();
// break if terminated
if (line==null)
break;
// Check : for debugging only
System.err.println("LINE : "+line);
// break if #
if (line.contains("#"))
{
// Get first part, part after, we dont care
int first=line.indexOf('#');
data+=line.substring(0, first);
break;
}
else
data += line;
}
// See the result
System.out.println("DATA:"+data);
The problem solved. readLine() function need end of string character <CR>. Just replacing "#" to "\n" solved the problem. Thanks to all great team.
you will never get null if the inputstream is from socket. Instead, the readLine() method will block until you get new data.
This is a quick one that stumps me. I've got a Java Program with the following code:
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
String file1 = args[0];
String file2 = args[1];
String output = args[2];
Writer writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(output), "utf-8"));
// Get the file
BufferedReader br1 = new BufferedReader(new FileReader(file1));
ArrayList<String> masterRBT = new ArrayList<String>();
// Read the files
while(br1.readLine() != null) {
masterRBT.add(br1.toString());
System.out.println(br1.toString());
}
Read the file (in this case, a .csv), and output it to the command line.
I use the command line to run the program, plus three parameters, using so (it only really uses the first one):
java -jar csvdiff.jar mainfile.csv subfile.csv output.csv
But then, it returns this:
java.io.BufferedReader#17dfafd1
Repeatedly, as if on loop. I tried putting in a Try/Catch error, but it still does the same - no errors. I've opened the .csv files, and verified its contents.
The CSV files are located in the same directory as the .jar file.
What am I missing?
because you are attempting to print an instance of BufferedReader not the data you are reading from it
Change
while(br1.readLine() != null) {
masterRBT.add(br1.toString());
System.out.println(br1.toString());
}
to
while((String line = br1.readLine()) != null) {
masterRBT.add(line);
System.out.println(line);
}
You're printing out br1.toString() - you're calling toString() on the BufferedReader itself. BufferedReader doesn't override toString(), so you're getting the implementation from Object, as documented:
The toString method for class Object returns a string consisting of the name of the class of which the object is an instance, the at-sign character #, and the unsigned hexadecimal representation of the hash code of the object. In other words, this method returns a string equal to the value of:
getClass().getName() + '#' + Integer.toHexString(hashCode())
That's not what you want. Presumably you actually want to print out the line that you've just read - but you've thrown that away by now. You want:
String line;
while((line = br1.readLine()) != null) {
masterRBT.add(line);
System.out.println(line);
}
Or as a for loop:
for (String line = br1.readLine(); line != null; line = br1.readLine()) {
masterRBT.add(line);
System.out.println(line);
}
As a general matter, if you start seeing ClassName#Number in output, that's almost certainly a similar problem of calling toString() on an object which doesn't override it.
You are not printing the line but the reader itself, to print the line change your code like this:
// Read the files
String line;
while((line = br1.readLine()) != null) {
masterRBT.add(line);
System.out.println(line);
}
Use this,
String str;
while((str=br1.readLine()) != null) {
masterRBT.add(str);
System.out.println(str);
}
Because BufferedReader.toString() just returns the class name and hash value of the object.
Use BufferedReader.readLine() to get the String instead.
So I tracked down the bugger, but I am no closer to understanding what is wrong. Here is what the compiler says:
Exception in thread "main" java.lang.NullPointerException at
BasicFile.Search(BasicFile.java:215) at
TestFile.main(TestFile.java:42)
Line 215 is the one that starts with while, first one.
String Search(String key) throws IOException {
int lines = 0;
String line = "";
String foundAt = "";
BufferedReader BF = new BufferedReader(new FileReader(f));
try {
while ((line = BF.readLine().toLowerCase()) != null) {
lines++;
//create tokenizer words with what is in line
StringTokenizer words = new StringTokenizer(line);
while(words.hasMoreTokens()) { //while words has tokens left
//go to next token and compare to key
if (words.nextToken().equals(key.toLowerCase()))
foundAt = foundAt + "\n" + lines + ":" + line;
//do nothing continue loop
}
}
BF.close();
} catch(FileNotFoundException e) {
}
return foundAt;
}
When your buffer reader runs out of lines it returns null. You are trying to call toLowerCase method on null which ends up throwing the null pointer exception.
Refactor your code in a way that it doesn't require you to execute toLowerCase before ensuring the line is non-null.
For example:
String next;
while ((next = BF.readLine()) != null) {
String line = next.toLowerCase();
// ...
}
while ((line = BF.readLine().toLowerCase()) != null)
What happens if BF.readline() returns null?
remove .toLowerCase() from the test
Please, stop it, your code is giving me cancer! There are a number of stylistic errors in the code that you need to fix.
First off in java, method names always begin with a lowercase letter. You are programming in Java, not C#, so you need to use the Java naming conventions. That means your method should be called search, not Search.
The same goes for variable names. What is BF supposed to mean, anyway? Replace it with in, please.
Next up, unless this method is in an object that itself represents that particular file, the global variable f should be passed as a parameter instead.
BufferedReader is AutoCloseable, so you should use a try-with-resources to deal with closing it.
You need to add a javadoc comment to it, documenting its parameters with #param, its return with #return, and exactly why it might need to throw an IOException with #exception.
Here is a mostly-fixed version of your code:
/**
* Needs Javadoc
*/
String search(String key, File f) throws IOException {
int lines = 0
String line = "";
String foundAt = "";
try(BufferedReader in = new BufferedReader(new FileReader(f)) {
while ((line = in.readLine().toLowerCase()) != null) { //the line in question
lines++;
StringTokenizer words = new StringTokenizer(line);
while(words.hasMoreTokens())
if (words.nextToken().equals(key.toLowerCase()))
foundAt = foundAt + "\n" + lines + ":" + line;
}
} catch(FileNotFoundException e){}
return foundAt;
}
Now, the problem here is that in.readline() returns a null sometimes. Calling a method on a null is always a NullPointerException. Therefore you get a NullPointerException when you attempt to call that null's missing toLowerCase() method.
You need to convert it toLowerCase after you ensure it is non-null.
I am reading an entire file and I want to use the line if it contains a specific string. I am unable to use the string because it is printing null outside the while loop, despite the fact that I have initialized it outside the loop.
FileInputStream wf = new FileInputStream(pr.getSplitDir() + listfiles[i]);
BufferedReader wbf = new BufferedReader(new InputStreamReader(wf));
String wfl = "";
while ((wfl = wbf.readLine()) != null) {
if (wfl.contains("A/C NO:")){
// System.out.println(wfl); // Here it is Printing the correct line
}
}
System.out.println(wfl); // Here it is printing null
Please help.
Try this below, You have to use another String or StringBuilder to get final out put
FileInputStream wf = new FileInputStream(pr.getSplitDir() + listfiles[i]);
BufferedReader wbf = new BufferedReader(new InputStreamReader(wf));
String wfl = "";
StringBuilder sb = new StringBuilder();
while ((wfl = wbf.readLine()) != null) {
if(wfl.contains("A/C NO:")){
//System.out.println(wfl);//Here it is Printing the correct line
sb.append(wfl);
}
}
System.out.println(sb.toString());//Here it is printing null
while ((wfl = wbf.readLine()) != null) {
if(wfl.contains("A/C NO:")){
//System.out.println(wfl);//Here it is Printing the correct line
}
}
Your while loop will exit only when wfl is null. So you have your answer!
To stop, your loop need wfl to be null, so when your loop has just stopped, wfl is obviously null.
Because your wbf.readLine when read null ,it assigns it wfl too and then compares to null
while ((wfl = wbf.readLine()) != null) { // here wbf.readLine when read null assigns to wfl
if(wfl.contains("A/C NO:")){
//System.out.println(wfl);//Here it is Printing the correct line
}
}
Do it like this,if you want to print outside while loop,
String test ="";
String wfl ="";
while ((wfl = wbf.readLine()) != null) {
if(wfl.contains("A/C NO:")){
//System.out.println(wfl);//Here it is Printing the correct line
}
test = test + wfl ; // for assigning all line
//test = wfl // for assigning last line
}
System.out.println(test); // it wil print the correct line