java string to int not doing anything - java

I have a .txt file which houses data as seen below. What I want to do is read from the file line by line then convert it to an int and display the result to screen.
The first system out line works fine, no problems their. The second however doesn't even print to screen. I guess theirs a issue with the string converting to int?
try (BufferedReader br = new BufferedReader(new FileReader("f.txt")))
{
String line;
while ((line = br.readLine()) != null) {
System.out.println(line); //does show
int change2Int = Integer.parseInt(line);
System.out.println(change2Int); //doesnt show
mp.getDataForDisplay(line);
}
}
catch (Exception expe)
{
expe.printStackTrace();
}
FIle:
0
1
4
2
5
The error it produces is a number format exception error.
java.lang.NumberFormatException: For input string: "0 "

The NumberFormatException that you're getting says what the problem is. Your input file also has some trailing whitespace characters in it, which is causing the parse to fail.
A simple way to prevent leading/trailing whitespace from tripping up your parse is to trim() your string before you attempt to parse it, like:
int change2Int = Integer.parseInt(line.trim());
As a general principle, it's a good idea to be permissive about what your program accepts as input, so that it can't be derailed by things like misplaced 'space' characters and other common human errors.

Your input string is "0 " which means there's a space. Use trim() before parsing. trim() is used to remove whitespace such as spaces.
eg:
int change2Int = Integer.parseInt(line.trim());

Related

how to read a set of lines with each line having CRLF(\r\n) as delimiter using java

Using java how can i read a paragraph with each line having a delimiter CRLF(\r\n).
For example
4\r\n
This\r\n
8\r\n
response\r\n
I want to extract 4 and store it into buffer and then read 8 and store for this paragraph.
Please help me.
Use BufferedReader.readLine() to just read the lines, or Scanner if you want to automically parse the numbers.
I'm not quite sure what output you require, but the BufferedReader class will allow you to read a text file line by line. There are several examples available on the internet.
The readLine method will do the following:
Reads a line of text. A line is considered to be terminated by any one of a line feed ('\n'), a carriage return ('\r'), or a carriage return followed immediately by a linefeed.
I'm not really sure of what you have to do but if you have to get the strings from your text you can do it by following my solution.
It may be not the best way but it works using StringTokenizer and by giving \r\n as delimiter.
StringTokenizer st1 = new StringTokenizer("4\r\n This\r\n 8\r\n response\r\n", "\r\n");
//iterate through tokens
while (st1.hasMoreTokens()) {
String str = st1.nextToken();
System.out.println(str);
}
This will print
4
This
8
response
This, of course, is useful if you're not reading from a file but you've just got the full string and you need to extract data from it.
If you're reading from a file you should check the other answers as BufferedReader.readLine is the right way.
EDIT:
Here's the new code:
StringTokenizer st1 = new StringTokenizer("4\r\n This\r\n 8\r\n response\r\n", "\r\n");
//iterate through tokens
while (st1.hasMoreTokens()) {
String str = st1.nextToken();
try{
//Integer.parseInt throws an exception in the input String doesn't represent a number so we catch the exception and we simply skip it. This will just output each number in your string.
int i = Integer.parseInt(str.trim());
System.out.println(i);
} catch (NumberFormatException e){}
}
Now it just ouputs:
4
8

Java String.split() - NumberFormatException

So, here's the thing, I've got this code:
public static void main(String[] args) {
try {
FileInputStream fstream = new FileInputStream("test.txt");
// Use DataInputStream to read binary NOT text.
BufferedReader br = new BufferedReader(new InputStreamReader(fstream));
String strLine = br.readLine();
String[] split = strLine.split(" ");
System.out.println(Integer.parseInt(split[0]));
in.close();
}
catch (Exception e) {//Catch exception if any
System.err.println("Error: " + e);
}
}
let's say I have a file named test.txt, with just "6 6". So, it reads first line and splits that line into two strings. The problem is that I can use Integer.parseInt for the split[1], but I can't use that method for split[0]
(System.out.println(split[0]) prints "6"), which outputs me an error of:
Error: java.lang.NumberFormatException: For input string: "6"
UPDATE:
It might be problem of eclipse, because if I compile my .java files in terminal with javac, I don't get any exceptions!:))
UPDATE2:
solved. something went wrong while saving with Kate. Don't know what, but gedit works better:D
Thank you all.
Just try with: hexdump -C test.txt if you have linux, you can see the non-printable chars you have.
Also the trim() answer it's fine.
I'd try the following to rule out spurious/unexpected characters:
.. setup/read code in main method...
String[] split = strLine.split(" ");
for (String s : split) {
System.out.println(String.format("[%s] => integer? %b", s, isInteger(s)));
}
... the rest of the main method....
private static boolean isInteger(String n) {
try {
Integer.parseInt(n);
} catch(NumberFormatException e) {
return false;
}
return true;
}
If you see anything inbetween the square brackets that isnt a number, or where the integer? returns false thats a likely the problem
This problem at the start of the file is usually due to a BOM, which some software (mainly Notepad in fact) like to put at the start of Unicode files.
Open the file in a good text editor and configure it to save the files without the BOM.
If you can't change the file, skip the first char when reading it.
If you are able to determine the actual encoding of the file you are reading, you can set it explicitly, so that any extra bytes are converted correctly into characters.
new InputStreamReader(new FileInputStream(...), <encoding>)

Why am I getting a NumberFormatException trying to parse an integer from string in Android?

I am looking for an update function for a custom ROM based tool. I used this code http://www.androidsnippets.com/check-for-updates-once-a-day as a base and soon realized that I couldn't use Dropbox for deployment with that code. So I modified the code to download a version.txt file from dropbox. The file contains a single number (the latest Version Code, in this case 11). I need to read that line and parse the string as an integer to compare with the current versionCode and trigger a download if an update exists.
All the code works, except for parsing the int from the txt file.
Heres my code:
private Thread checkUpdate = new Thread() {
public void run() {
try {
File sdcard = Environment.getExternalStorageDirectory();
File file = new File(sdcard,"BPversion.txt");
StringBuilder text = new StringBuilder();
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
while ((line = br.readLine()) != null) {
text.append(line);
int curVersion = getPackageManager().getPackageInfo("com.JB15613.BPcolorTool", 0).versionCode;
System.out.println(line);
int newVersion = 0;
System.out.println(line);
try {
newVersion = Integer.parseInt(line);
System.out.println(line);
} catch(NumberFormatException nfe) {
System.out.println("Exception " + nfe);
}
if (newVersion > curVersion) {
mHandler.post(showUpdate);
}
}
} catch (Exception e) {
Log.d("ANDRO_ASYNC", "Caught exception");
}
}
And I get this exception:
Exception java.lang.NumberFormatException: Invalid int: "11"
When I apply breakpoints and run the debugger, it crashes at the parseInt line.
11 looks like a valid int to me!
Any help is greatly appreciated!
line ends CRLF ,so , need call function trim() in String ..
int newVersion = Integer.parseInt(line.trim());
I just want to add to what has already been stated:
Your problem is that your 11 is not able to parse to an int, the underlying root of which is that you are parsing white space as part of your string.
As already stated the trim() method should remove the problem but If you wanted to know what was causing the problem and why this fixes it then that is the reason.
You are not trying to parse "11", you are parsing something like "11 " or " 11" which is a different thing. The spaces from the file you are reading from are being included in your string as it is passed into the parseInt method.
Again, I know this has been answered but I thought this additional information would still be useful.
Try to print the value of line in the logcat or screen or ui.
Check what will be coming.A valid int is coming or any other is coming.
i think line does not cotains valid int.
Exception java.lang.NumberFormatException
The above exception is thrown due to invalid int format or number format.
Check the values of line

Java: Copy strings from a file to another without losing the 'newline format'

Sorry in advance if the title is misleading/wrong but this is the best I can do after a really long day spent practicing with Java. (my brain is melting)
I put this code togheter to read a file and copy it into another file, skipping the line/lines that begins with a given string (BeginOfTheLineToRemove). It actually works and remove the desired line, but, for some reason, it forgets about the \n (newline). Spacing and symbols are copied. I can't figure it out. I really hope someone will help. cheers from a java newb from italy ;)
public void Remover(String file, String BeginOfTheLineToRemove) {
File StartingFile = new File(file);
File EndingFile = new File(StartingFile.getAbsolutePath() + ".tmp");
BufferedReader br = new BufferedReader(new FileReader(file));
PrintWriter pw = new PrintWriter(new FileWriter(EndingFile));
String line;
while ((line = br.readLine()) != null) {
if (line.startsWith(LineToRemoveThatBeginWithThis)) {
continue;
}
pw.write(line);
}
pw.close();
br.close();
}
Use pw.println instead of pw.write. println adds new line character after it writes content.
You are using PrintWriter.write() to write the lines - This does not by default write newline at the end. Use println() instead.
This will probably help you.
The BufferedReader.readLine() method does not read any line termination characters. So therefore your line will not contain any termination characters.
BufferedReader#readLine documentation says:
Returns: A String containing the contents of the line, not including any line-termination characters, or null if the end of the stream has been reached
That is, the reader strips the line termination characters from your Strings, so you need to manually add them again:
// \n on Linux/Mac, \r\n on Windows
String lineSep = System.getProperty("line.separator");
pw.write(line);
pw.write(lineSep);
BufferedReader.readLine() uses the newline to identify the end of the line, and the string that it returns does not contain this newline. The newline is a separator, so it is not considered part of the data.
To compensate for this, you can add a newline to your output, like so:
while((line = br.readLine()) != null) {
if(line.startsWith(LineToRemoveThatBeginWithThis)) continue;
pw.write(line);
pw.println();
}
The extra call to PrintWriter.println() will print a newline after you write out your line of text.
Outside the loop get the system's line seperator:
String lineSeparator = System.getProperty("line.separator");
Then append that to the line you've read in:
pw.write(line+lineSeparator);

Counting Words and Newlines In A File Using Java?

I am writing a small java app which will scan a text file for any instances of particular word and need to have a feature whereby it can report that an instance of the word was found to be the 14th word in the file, on the third line, for example.
For this i tried to use the following code which i thought would check to see whether or not the input was a newline (\n) character and then incerement a line variable that i created:
FileInputStream fileStream = new FileInputStream("src/file.txt");
DataInputStream dataStream = new DataInputStream(fileStream);
BufferedReader buffRead = new BufferedReader(new InputStreamReader(dataStream));
String strLine;
String Sysnewline = System.getProperty("line.separator");
CharSequence newLines = Sysnewline;
int lines = 1;
while ((strLine = buffRead.readLine()) != null)
{
if(strLine.contains(newLines))
{
System.out.println("Line Found");
lines++;
}
}
System.out.println("Total Number Of Lines In File: " + lines);
This does not work for, it simply display 0 at the end of this file. I know the data is being placed into strLine during the while loop as if i change the code slightly to output the line, it is successfully getting each line from the file.
Would anyone happen to know the reason why the above code does not work?
Read the javadocs for readLine.
Returns:
A String containing the contents of the line, not including any line-termination characters, or null if the end of the stream has been reached
readLine() strips newlines. Just increment every iteration of the loop. Also, you're overcomplicating your file reading code. Just do new BufferedReader(new FileReader("src/file.txt"))

Categories

Resources