This seemed like a really trivial issue, but I'm trying to write an array of booleans to a file and then read them back into the array. I can verify that the file is being created properly:
true
false
true
false
false
false
But when I try to read it back, I end up with an array completely full of false. Here's my reading code:
bools = new boolean[bools.length];
try {
BufferedReader reader = new BufferedReader(new FileReader(file));
String temp;
int i = 0;
while (null != (temp = reader.readLine())) {
bools[i] = Boolean.parseBoolean(temp);
// output what you read
if (bools[i]) {
System.out.println("true!");
} else {
System.out.println("false!");
}
}
reader.close();
} catch (FileNotFoundException ex) {
Logger.getLogger(BooleanFiles.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(BooleanFiles.class.getName()).log(Level.SEVERE, null, ex);
}
// now output the resulting array
for (int i = 0; i < bools.length; i++) {
if (bools[i]) {
System.out.println("true!");
} else {
System.out.println("false!");
}
}
And here's the output I get:
true!
false!
true!
false!
false!
false!
false!
false!
false!
false!
false!
false!
The part that drives me bonkers is the array is set properly when I check it as I read (in the while loop), but it's wrong when I check the array at the end (in the for loop).
It may also be helpful to know that bools is a property of the class
Please excuse my noobishness.
Thanks!
while (null != (temp = reader.readLine())) {
bools[i] = Boolean.parseBoolean(temp);
// output what you read
System.out.println(bools[i]);
i++;
}
You are putting everything at the same location. Increment your iterator variable and it will work.
Your not updating i value. First time your getting properly because your printing values directly from file.
Related
while(true)
{
String input = "";
try {
input = in.readLine();
} catch (IOException e1) {
// TODO Auto-generated catch block
System.out.println(e1 + "Exception occured when reading user input");
}
// Sleep
try
{
Thread.sleep(USER_THROTTLE);
}
catch(Exception e)
{
System.out.println(toString()+" has input interrupted.");
}
if(input .equals("w")){action_event(input);}
if(input .equals("a")){action_event(input);}
if(input .equals("s")){action_event(input);}
if(input .equals("d")){action_event(input);}
if(input .equals("eat")){action_event(input);}
if(input .equals("drink")){action_event(input);}
if(input .equals("place")){action_event(input);}
if(input .equals("swim")){action_event(input);}
if(input .equals("command_kill")){action_event(input);}
if(input .equals("help")){action_event(input);}
}
}
Here is the stack trace
Exception in thread "Thread-1" java.lang.NullPointerException
at Platypus_User$Inport.run(Platypus_User.java:64)
This is being ran in Eclipse on Mac OSX.
A Null Pointer Exception occurs following the second catch block where the string is compared to "w" then if it is "w" the action_event method is called.
I have no clue why this would be happening. I would appreciate any advice.
I guess in is a BufferedReader. readLine will return null if End Of The Stream is reached.
See BufferedReader documentation
BufferedReader.readLine() can return null, so check for null on input.
First, avoid repetitions in code. You can collect all allowed inputs in one Set and then just check if it contains particular value--thus making code look much more readable, short and clean.
Second, you need to perform null check, because in.read() can return null as mentioned in other answers. null input could also be used for termination of while loop.
So I would rewrite your code as following:
Set<String> allowedInputs
= new HashSet<>(Arrays.asList("w", "a", "s", "d", "eat")); // <- add remaining allowed inputs here
String input = "";
while (input != null) {
try {
input = in.readLine();
} catch (IOException e1) {
System.out.println(e1 + "Exception occured when reading user input");
}
try {
Thread.sleep(USER_THROTTLE);
} catch(Exception e) {
System.out.println(toString() + " has input interrupted.");
}
if (input != null && allowedInputs.contains(input)) { // <- check if input is allowed
action_event(input);
}
}
Never invoke methods on objects which are not initialized. input may hold a null value. So before comparing you must make sure that object is not null.
Best approach to handle such situations would be by comparing a constant value with "input" instead of comparing input with a constant value.
eg "w".equals(input)
I am trying to write a new document based on the Objects I have in my side2[] array.
Now unfortunately, some indexes are null in this array, and when it hits one of them, it just gives me a NullPointerException. This array has 10 indexes, but in this case not all of them are needed. I have tried the try catch statement in hopes of continuing after it comes across a null, but it still stops execution and doesn't write a new document.
The stack (srail) that is part of the object contains the data I want to print out.
Here is my code:
// Write to the file
for(int y=0; y<=side2.length; y++)
{
String g = side2[y].toString();
if(side2[y]!=null){
while(!side2[y].sRail.isEmpty())
{
out.write(side2[y].sRail.pop().toString());
out.newLine();
out.newLine();
}
out.write(g);
}
}
//Close the output stream/file
out.close();
}
catch (Exception e) {System.err.println("Error: " + e.getMessage());}
The problem is that the code calls toString() on the side2[y] object before checking it for null. You can skip null objects by adding a condition at the top of the loop, like this:
for(int y=0; y<=side2.length; y++) {
if(side2[y] == null) {
continue;
}
String g = side2[y].toString();
// No further checks for null are necessary on side2[y]
while(!side2[y].sRail.isEmpty()) {
out.write(side2[y].sRail.pop().toString());
out.newLine();
out.newLine();
}
out.write(g);
}
Why is ArrayList not being written into "MyCalendar.txt"? Even when I use out.write() it still returns false but does not write to the file.
import java.util.*;
import java.io.*;
public static Boolean addAppointment(ArrayList<String> calendar,
String specifiedDay,
String specifiedTime) {
PrintWriter out = new PrintWriter("myCalendar.txt"); //declare calendar file
for (int i = 0; i<calendar.size(); i++) {
String index = calendar.get(i);
if (index.equals(specifiedDay + "" + specifiedTime))
{
out.println(specifiedDay + "" + specifiedTime);
return false;
}
}
return true;
}
Below 2 are important to flush data to file and close the stream
out.flush();
out.close();
Regards,
you forgot to close it:
out.close()
So, a couple of things here.
If you're using Java 7, you should consider using try-with-resources. This will absolutely ensure that your PrintWriter is closed after you're done.
try (PrintWriter out = new PrintWriter("somefile.txt")) {
// code
} catch (FileNotFoundException e) {
System.out.println("Bang!");
}
Next, there are a few cases in which the file could not be written to, either in part or at all:
calendar.size() == 0
index.equals(specifiedDay + "" + specifiedTime)
If the first condition is met, nothing is written and the method happily returns true. Probably not what you expected.
If the second condition is met, you write the first element, and early return. It would probably be a better idea to place that in your loop condition, and return the return value when you're done looping.
int i = 0;
boolean good = true;
while(good && i < calendar.size()) {
// critical actions
String index = calendar.get(i);
if(index.equals(specifiedDay + "" + specifiedTime)) {
good = false;
}
}
// other code
return good;
If that condition is never met, then nothing is ever written to the file.
The default behavior of PrintWriter is not to automatically flush the buffer. See the PrintWriter Documentation for more details.
Alternatively, you might have a data issue:
String index = calendar.get(i);
if (index.equals(specifiedDay + "" + specifiedTime))
If this condition isn't satisfied, you won't print anything out. Have you made sure this condition is true?
I need to read a text file line by line till I find a specific string. I'm using BufferedReader.readLine() but when I debug I find that it starts from the third line in the file and skips lines after that.
Here is my code:
try {
reader = new BufferedReader(new FileReader(path));
String line1 = null;
while ((line1 = reader.readLine()) != null) {
if (line1.toString() == invocation0) {
found = true;
return false;
} else if (line1 == invocation1) {
found = true;
return true;
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (reader != null)
try {
reader.close();
} catch (IOException e) {
}
}
I would really appreciate any help, as I tried many different solutions for this and still can't solve this issue.
the content of the file is like:
.//============================================================================
.// File: abc.mark
.// Description: anything
.// Notice: anything
.// .//============================================================================
.invoke RemoveClass("Properties",0)
if(line1.equals(invocation0))
Use equals() method for String value comparison.
Also, instead of return within the if, you can use a break. This is just a suggestion though.
BufferedReader should not be skipping the anything. Unfortunately you are the one who is making read method to skip the line. The equlaity operator == will not compare the content of any two strings, rather it compares whether they are of same object. You could possibly avoid it in two ways.
Call the intern() on invocation0 (line1 object should have been interned before anyway)
More precisely use equals method line1.equals(invocaton0)
This link may be of some help for you to understand it better.
I'm trying to do something reallllly simple that apparently is extremely difficult in android.
I just want to compare two strings to see if they are equal.
I have a temp variable with the value "Location"
I have debugged this and it does indeed contain Location...
So I tried this at first
if(temp == "Location") { //do something }
But I already know that doesn't work. I then tried all the possible functions for a string such as:
.equals
.contains
.ignoreCaseEquals
etc...
If anyone has any idea what to do please help. This is really getting annoying.
EDIT:
Here is the function where I'm comparing the strings for those of you who want to see.
public String[] getData(){
try {
int tempGroupCount = 0;
URL food_url = new URL (Constants.SERVER_DINING);
BufferedReader my_buffer = new BufferedReader(new InputStreamReader(food_url.openStream()));
temp = my_buffer.readLine();
// prime read
while (temp != null ){
// check to see if readline equals Location
Log.w("HERasdfsafdsafdsafE", temp);
// start a new location
if (temp.equals("Location")
{
groups[tempGroupCount] = temp;
tempGroupCount++;
}
Log.w("HERasdfsafdsafdsafE", temp);
//start for-loop to test to get child info
//for(temp = my_buffer.readLine(); temp != "Location" && temp != null; groupCount++, childrenCount++){
//children[groupCount][childrenCount] = temp;
//}
temp = my_buffer.readLine();
}
my_buffer.close();
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
Log.e("IO EXCEPTION", "Exception occured in MyExpandableListAdapter:" + e.toString());
}
return groups;
}
equals does work. If temp.equals("Location") returns false, then your temp variable does not refer to a string with the value "Location".
There may be unprintable characters or other oddities about the string - I suggest you look at the length of the string to check. Alternatively, there can be other characters which look like the ASCII characters, but aren't. In the debugger, try examining the array and get at the underlying char array - check the Unicode value of each character.
if(temp.equals("Location"))
{
//your code here
}
does not work
try this
if(temp.contains("Location"))
{
//your code here
}
try like
if(temp.equals("Location")) { //do something }
and
while (!temp.equals("")){
if your variable temp is a String, you can also used the method compareTo(String).
if (temp.compareTo("Location") == 0)
{
//do something
}
I am doing same scenario , its working fine.
String result = responsePrimitiveData.toString();
if(!result.equals("0")){
}
Try doing this:
if (temp.toLowerCase().compareTo("location") == 0)
public String[] getData(){
try {
int tempGroupCount = 0;
URL food_url = new URL (Constants.SERVER_DINING);
BufferedReader my_buffer = new BufferedReader(new InputStreamReader(food_url.openStream()));
temp = my_buffer.readLine();
// prime read
while (temp != null ){
// check to see if readline equals Location
Log.w("HERasdfsafdsafdsafE", temp);
// start a new location
if (temp.toString().equalsIgnoreCase("Location")
{
groups[tempGroupCount] = temp;
tempGroupCount++;
}
Log.w("HERasdfsafdsafdsafE", temp);
//start for-loop to test to get child info
//for(temp = my_buffer.readLine(); temp != "Location" && temp != null; groupCount++, childrenCount++){
//children[groupCount][childrenCount] = temp;
//}
temp = my_buffer.readLine();
}
my_buffer.close();
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
Log.e("IO EXCEPTION", "Exception occured in MyExpandableListAdapter:" + e.toString());
}
return groups;
}
first try to convert "temp" into string then compare it, apply this may helps you
you may try the following to find out where your problem is.
final String LOCATION = "Location"; // just to make sure we use the very same character sequence
if (temp.equals(LOCATION)
{
/* your code here */
}
else
{
System.out.println("Location : " + Arrays.toString(LOCATION.getBytes(Charset.forName("UTF-8"))));
System.out.println("temp : " + Arrays.toString(temp.getBytes(Charset.forName("UTF-8"))));
}
This should print the byte representation of both Strings to standard out. If equals() returns false, the strings differ. Because of unprintable characters or similar looking characters it's sometimes difficult to find the difference. But the byte representation should show you.
(I'm not an android programmer, so I hope the functions exist on android JVM. And sorry for any typos and missing brackets - if any ;-)