converting one line string into individual integers - java

if i have this line in a file: 2 18 4 3
and i want to read it as individual integers, how could i?
i'm using bufferreader:
BufferedReader(new FileReader("mp1.data.txt"));
i have tried to use:
BufferedReader(new RandomAccessFile("mp1.data.txt"));
so i can use the method
.readCahr();
but i got an error
if i use
int w = in.read();
it will read the ASCII, and i want it as it is(in dec.)
i was thinking to read it as a string first, but then could i separate each number?
also i was thinking to let each number in a line, but the file i have is long with numbers

Consider using a Scanner:
Scanner scan = new Scanner(new File("mp1.data.txt"));
You can then use scan.nextInt() (which returns an int, not a String) so long as scan.hasNextInt().
No need for that ugly splitting and parsing :)
However, note that this approach will continue reading integers past the first line (if that's not what you want, you should probably follow the suggestions outlined in the other answers for reading and handling only a single line).
Furthermore, hasNextInt() will return false as soon as a non-integer is encountered in the file. If you require a way to detect and handle invalid data, you should again consider the other answers.

It's important to approach larger problems in software engineering by breaking them into smaller ones. In this case, you've got three tasks:
Read a line from the file
Break it into individual parts (still strings)
Convert each part into an integer
Java makes each of these simple:
Use BufferedReader.readLine() to read the line as a string first
It looks like the splitting is as simple as splitting by a space with String.split():
String[] bits = line.split(" ");
If that's not good enough, you can use a more complicated regular expression in the split call.
Parse each part using Integer.parseInt().
Another option for the splitting part is to use the Splitter class from Guava. Personally I prefer that, but it's a matter of taste.

You can split() the String and then use the Integer.parseInt() method in order to convert all the elements to Integer objects.
try {
BufferedReader br = new BufferedReader(new FileReader("mp1.data.txt"));
String line = null;
while ((line = br.readLine()) != null) {
String[] split = line.split("\\s");
for (String element : split) {
Integer parsedInteger = Integer.parseInt(element);
System.out.println(parsedInteger);
}
}
}
catch (IOException e) {
System.err.println("Error: " + e);
}

Once you read the line using BufferedReader, you can use String.split(regex) method to split the string by space ("\\s").
for(String s : "2 18 4 3".split("\\s")) {
int i = Integer.parseInt(s);
System.out.println(i);
}

If you use Java 7+, you can use this utility method:
List<String> lines = Files.readAllLines(file, Charset.forName("UTF-8"));
for (String line: lines) {
String[] numbers = line.split("\\s+");
int firstNumber = Integer.parseInt(numbers[0]);
//etc
}

Try this;
try{
// Open the file that is the first
FileInputStream fstream = new FileInputStream("textfile.txt");
BufferedReader br = new BufferedReader(new InputStreamReader(fstream));
String strLine;
//Read File Line By Line
while ((strLine = br.readLine()) != null) {
//split line by whitespace
String[] ints = strLine.split(" ");
int[] integers = new int[ints.length];
// to convert from string to integers - Integer.parseInt ("123")
for ( int i = 0; i < ints.length; i++) {
integers[i] = Integer.parseInt(ints[i]);
}
// now do what you want with your integer
// ...
}
in.close();
} catch (Exception e) {//Catch exception if any
System.err.println("Error: " + e.getMessage());
}

Related

How to read every second line from a file in java

Can someone tell me how to read every second line from a file in java?
BufferedReader br = new BufferedReader(new FileReader(file));
String line = br.readLine();
while(line != null){
//Do something ..
line = br.readLine()
}
br.close
One simple way would be to just maintain a counter of number of lines read:
int count = 0;
String line;
while ((line = br.readLine()) != null) {
if (count % 2 == 0) {
// do something with this line
}
++count;
}
But this still technically reads every line in the file, only choosing to process every other line. If you really only want to read every second line, then something like RandomAccessFile might be necessary.
You can do it in Java 8 fashion with very few lines :
static final int FIRST_LINE = 1;
Stream<String> lines = Files.lines(path);
String secondLine = lines.limit(2).skip(FIST_LINE).collect(Collectors.joining("\n"));
First you stream your file lines
You keep only the two first lines
Skip the first line
Note : In java 8, when using Files.lines(), you are supposed to close the stream afterwards or use it in a try-with-resource block.
This is similar to #Tim Biegeleisen's approach, but I thought I would show an alternative to get every other line using a boolean instead of a counter:
boolean skipOddLine = true;
String line;
while ((line = br.readLine()) != null) {
if (skipOddLine = !skipOddLine) {
//Use the String line here
}
}
This will toggle the boolean value every loop iteration, skipping every odd line. If you want to skip every even line instead you just need to change the initial condition to boolean skipOddLine = false;.
Note: This approach only works if you do not need to extend functionality to skip every 3rd line for example, where an approach like Tim's would be easier to modify. It also has the downside of being harder to read than the modulo approach.
This will help you to do it very well
You can use try with resource
You can use stream api java 8
You can use stream api supplier to use stream object again and again
I already hane added comment area to understand you
try (BufferedReader reader =
new BufferedReader(
new InputStreamReader(
new ByteArrayInputStream(x.getBytes()),
"UTF-8"))) { //this will help to you for various languages reading files
Supplier<Stream<String>> fileContentStream = reader::lines; // this will help you to use stream object again and again
if (FilenameUtils.getExtension(x.getOriginalFilename()).equals("txt")) { this will help you to various files extension filter
String secondLine = lines.limit(2).skip(FIST_LINE).collect(Collectors.joining("\n"));
String secondLine =
fileContentStream
.get()
.limit(2)
.skip(1)// you can skip any line with this action
.collect(Collectors.joining("\n"));
}
else if (FilenameUtils.getExtension(x.getOriginalFilename()).equals("pdf")) {
} catch (Exception ex) {
}

Java NumberFormatException Error String to Float

Taking in a list of strings and converting them to a float and storing the values. I get this error when hitting the second value I want to store. Below is the code and the text file I'm reading from:
public static void readCities() {
StringBuilder sb = new StringBuilder();
BufferedReader br = null;
try {
br = new BufferedReader(new FileReader("C:/Users/Luke/workspace/Traveling Sales Person/Destinations/11PointDFSBFS.tsp"));
String line;
while ((line = br.readLine()) != null) {
if (sb.length() > 0) {
sb.append("\n");
}
sb.append(line);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (br != null) {
br.close();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
String contents = sb.toString();
String[] parts = contents.split("NODE_COORD_SECTION");//splits into locations
String[] locations = parts[1].split(" ");
int counter = 0;
for (int i = 1; i < locations.length; i++) {
cities[counter] = new City(Float.parseFloat(locations[i+1]), Float.parseFloat(locations[i+2]));
counter++;
}
}
Code error:
Exception in thread "main" java.lang.NumberFormatException: For input string: "63.860370
2
at sun.misc.FloatingDecimal.readJavaFormatString(FloatingDecimal.java:2043)
at sun.misc.FloatingDecimal.parseFloat(FloatingDecimal.java:122)
at java.lang.Float.parseFloat(Float.java:451)
at TSP.readCities(TSP.java:132)
at TSP.main(TSP.java:28)
As all the commenters already said: Without the actual data it's more or less guessing, what is the problem, but with your code and the error-message some things can be said already, what you should do independly:
You read in all the lines and put them into a StringBuilder including a new line-break. Later on you do splits, but you never remove this line-break, so it is going to end up in the data you try to parse as float. This will lead to a parsing error, because spaces and other whitespaces are not removed. The easiest way to do this without changing too much in your code is by trimming the values:
cities[counter] = new City(Float.parseFloat(locations[i+1].trim()), Float.parseFloat(locations[i+2],trim()));
BTW: What's the reason for creating a new variable counter that is essentially i-1 and using i+1 and i+2 later on? Makes reading your code a bit harder, because you expect some additional logic where entries are skipped which isn't there.
According to the error-message the problem is a leading quotation mark and a newline. You can't say if that error occurred for the first or the second of the two values that are parsed and without the original line(s) of the input file it's hard to say, what is going on, but maybe I gave you enough hints to allow you to progress with your code.
If not we need more informations, especially the line(s) that produce this error, so analysing your code becomes possible.

NumberFormatException error from reading a file

I've been getting a NumberFormatException error when I try to read some data from a text file and convert it to an integer. From what I've seen other people say, this error is caused when an empty string is converted to an integer using pasreInt(). But I've been able to print the string '1' from the file into the output. Does anyone know why I'm getting this error even though the string doesn't seem to be empty? Here's my code:
try {
//Retrieve Info
FileReader fr = new FileReader("BankInfo.txt");
BufferedReader br = new BufferedReader(fr);
//Skip specified number of lines
for(int i=0; i<line; i++) {
br.readLine();
}
//Print the string to output
String holderStr = br.readLine();
System.out.println(holderStr);
//The line creating the NumberFormatException
totalBalNum = (double)Integer.parseInt(holderStr);
br.close();
//Read Whole File
BufferedReader br2 = new BufferedReader(fr);
while((str = br.readLine()) != null) {
arrList.add(str);
}
br2.close();
} catch (IOException | NumberFormatException e) {
System.out.println("ERROR! Problem with FileReader. " + e);
}
I know my code is probably really sloppy and inefficient too... I'm a little bit of a noob.
Ok, I think converting string into Integer and then typecasting it to double is causing the error. Why don't you just convert the string to double.
Also you must trim the line while reading it to avoid any spaces.
String holderStr = br.readLine().trim();
System.out.println(holderStr);
totalBalNum = Double.parseDouble(holderStr);
use replaceAll() to convert everything but digits to empty character.
holderStr.replaceAll("\\D+","");
eg.
String extra34345 dfdf will be converted to 34345
String ab34345ba will be converted to 34345
String \n34345\n will be converted to 34345
The code
String holderStr = br.readLine();
//this line will remove everything from the String, other than Digits
holderStr= holderStr.replaceAll("\\D+","");
System.out.println(holderStr);

Read Strings separated by newline using BufferedReader into a String array

I've read number of such questions but they are all about reading inputs from a txt file. I want to read input from user and not from the file.
I've input like following:
6 //number of total Strings to store in array
babu
anand
rani
aarti
nandu
rani
I've tried the following code to take such input in a String array:
int n = in.nextInt(); // n= 6 here
String[] s = new String[n]; //String array of size 6 here
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
try{
s = br.readLine().split("\\s");
}
catch(Exception e){
System.out.println(e);
}
Is the regex provided to the split() is correct or not? What I'm missing here? If this is not correct approach than what should I do for this problem?
Regex are using backslashes (\) while you used slashes //s, correct one is \\s.
But this split is not needed, you just need the readLine, and you will get what you need (assuming you don't want to split words in the line).
You should use a loop to read all the data (and get rid of Scanner, that you appear to have in the in variable):
String[] s = null
try (BufferedReader br = new BufferedReader(new InputStreamReader(System.in)) {
int n = Integer.parseInt(br.readLine());
for (int line = 0; line < n; line++) {
s[line] = br.readLine();
}
} catch(Exception e){
System.out.println(e);
}
Move the third line before the first one.
Then use this in your new second line:
int n = Integer.parseInt(br.readLine());
And, of course, you need a loop to put your input strings into an array.
This should help.

How can I recognize a special delimiter string when reading from a file of strings?

I want to read strings from a file. When a certain string (><) is found, I want to start reading integers instead, and convert them to binary strings.
My program is reading the strings in and saving them in an ArrayList successfully, but
it does not recognise the >< symbol and therefore the reading of the binary strings is not successful.
The Code
try {
FileInputStream fstream = new FileInputStream(fc.getSelectedFile().getPath());
// Get the object of DataInputStream
DataInputStream ino = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(ino));
String ln;
String str, next;
int line, c =0;
while ((ln = br.readLine()) != null) {
character = ln;
System.out.println(character);
iname.add(ln); // arraylist that holds the strings
if (iname.get(c).equals("><")) {
break; // break and moves
// on with the following while loop to start reading binary strings instead.
}
c++;
}
String s = "";
// System.out.println("SEQUENCE of bytes");
while ((line = ino.read()) != -1) {
String temp = Integer.toString(line, 2);
arrayl.add(temp);
System.out.println("telise? oxii");
System.out.println(line);
}
ino.close();
} catch (Exception exc) { }
The file I'm trying to read is for example:
T
E
a
v
X
L
A
.
x
"><"
sequence of bytes.
Where the last part is saved as bytes and in the textfile appears like that. no worries this bit works. all the strings are saved in a new line.
< is two characters and iname.get(c) is only one character.
What u should do is test if ln equals > and then another test if the next character equals < . If both test pass then break out of the loop.
you will have to becarefull
Use a Scanner. It allows you to specify a delimiter, and has methods for reading input tokens as String or int.
Could you not do something like:
while ((ln = br.readLine()) != null){
character=ln;
System.out.println(character);
//
// Look for magic characters >< and stop reading if found
//
if (character.indexOf("><") >= 0) {
break;
}
iname.add(ln);
}
This would work if you didn't want to add the magic symbol to your ArrayList. Your code sample is incomplete - if you're still having trouble you'd need to post the whole class.

Categories

Resources