I have read a file into an array but am wondering how to parse certain values from that array.
My code:
...
try{
...
String strLine;
String delims= "[ ]+";
//parsing it
ArrayList parsedit = new ArrayList();
while((strLine=br.readLine())!=null){
System.out.println("Being read:");
System.out.println(strLine);
parsedit.add(strLine.split(delims));
}
System.out.println("Length:" + parsedit.size());
in.close();
...
The files that I am reading in are like this:
a b c d e f g
1 2 3 4 5 6 7
1 4 5 6 3 5 7
1 4 6 7 3 2 5
Which makes the output like this:
How many files will be input? 1
Hey, please write the full path of the input file number1!
/home/User/Da/HA/file.doc
Being read:
a b c d e f g
Being read:
1 2 3 4 5 6 7
...
Length:4
I would like to parse out this data and just have the first and fifth values remaining, so that it would read like this instead:
a e
1 5
Does anyone have a recommendation on how to go about it?
EDIT:
Following some of the suggestions I have changed my code to:
public static void main(String[] args) {
System.out.print("How many files will be input? ");
Scanner readIn=new Scanner(System.in);
int input=readIn.nextInt();
int i=1;
while(i<=input){
System.out.println("Hey, please write the full path of the input file number" + i + "! ");
Scanner fIn=new Scanner(System.in);
String fileinput=fIn.nextLine();
try{
FileInputStream fstream=new FileInputStream(fileinput);
DataInputStream in=new DataInputStream(fstream);
BufferedReader br=new BufferedReader(new InputStreamReader(in));
String strLine;
String delims= "[ ]+";
ArrayList parsedit = new ArrayList();
while((strLine=br.readLine())!=null){
System.out.println("Being read:");
System.out.println(strLine);
parsedit.add(strLine.split(delims));
}
String[] splits=strLine.split(delims);
System.out.println("Length:" + splits.length);
in.close();
}
catch(Exception e){
System.err.println("Error: " + e.getMessage());
}
i++;
}
}
}
This doesn't give back any errors but it doesn't seem to be working all the same. Am I missing something silly? The output is this:
How many files will be input? 1
Hey, please write the full path of the input file number1!
/home/User/Da/HA/file.doc
Being read:
a b c d e f g
Being read:
1 2 3 4 5 6 7
...
But despite the fact that I have a line to tell me the array length, it never gets printed, which tells me I just ended up breaking more than I fixed. Do you know what it is that I may be missing/forgetting?
The split() function returns an array of strings representing the tokens obtained from the original String.
So, what you want is to keep only the first and the 5th token (splits[0] & splits[4]):
String[] splits = strLine.split(delims);
//use the splits[0] & splits[4] to create the Strings you want
Regarding your update, replace this:
while((strLine=br.readLine())!=null){
System.out.println("Being read:");
System.out.println(strLine);
parsedit.add(strLine.split(delims));
}
With this:
while((strLine=br.readLine())!=null){
System.out.println("Being read:");
String splits[] = strLine.split(delims);
System.out.println(splits[0]+" "+splits[4]);
parsedit.add(splits);
}
You can try this
String[] line = s.split("\\s+");
This way all your elements will be stored in a sequence in the array line.
This will allow you to access whatever element you want.
You just need to get the first and the fifth value out of the String[] returned by strLine.split(delims).
(I am assuming you know what you are doing in your current code. You are assuming that each line will contains the same number of "columns", delimited by at least 1 space character. It is a fair assumption, regardless.)
Related
I want to read a String from a file. String contains several floating numbers separated with whitespace. Then I want to split it into several Strings, containing one number each and parse them to double. numbers.length() shows that my String is 1 symbol longer than it actualy is in the file. And this symbol is an invisible whitespace I cant get rid of. First element in the array has it too, and trim() doesnt help. I tried to trim every element in array, doesnt help. I cant parse this array into numbers because of this whitespace, Im getting an exception. I see that this is actualy a whitespace in the beginning only if I split String numbers or the first element of the array into chars. Beginner programmer here.
BufferedReader reader1 = new BufferedReader(new InputStreamReader(System.in));
String file1 = reader1.readLine();
reader1.close();
BufferedReader reader2 = new BufferedReader(new FileReader(file1));
String numbers = reader2.readLine();
reader2.close();
System.out.println(numbers.length());
String[] array = numbers.trim().split("\\s+");
First Line Output Full code of the class. And I added what I get in IDEA. That whitespace or whatever that goes before '4' in printing array[0] is my problem.
41
4234.234 9
2341.452 8
98234.4 7
2378.34 7
114.32 6
4
2
3
4
.
2
3
4
Process finished with exit code 0
public class Solution {
public static void main(String[] args) throws IOException{
BufferedReader reader1 = new BufferedReader(new InputStreamReader(System.in));
String file1 = reader1.readLine();
reader1.close();
BufferedReader reader2 = new BufferedReader(new FileReader(file1));
String numbers = reader2.readLine();
reader2.close();
System.out.println(numbers.length());
String[] array = numbers.trim().split("\\s+");
for(int i = 0; i < array.length; i++) {
System.out.println(array[i] + " " + array[i].length());
}
char[] ch = array[0].toCharArray();
for(char c:ch) {
System.out.println(c);
}
}
}
Why does Java String.split() generate different results when working with string defined in code versus string read from a file when numbers are involved? Specifically I have a file called "test.txt" that contains chars and numbers separated by spaces:
G H 5 4
The split method does not split on spaces as expected. But if a string variable is created within code with same chars and numbers separated by spaces then the result of split() is four individual strings, one for char and number. The code below demonstrates this difference:
import java.io.File;
import java.io.FileReader;
import java.io.BufferedReader;
public class SplitNumber {
//Read first line of text file
public static void main(String[] args) {
try {
File file = new File("test.txt");
FileReader fr = new FileReader(file);
BufferedReader bufferedReader = new BufferedReader(fr);
String firstLine;
if ((firstLine = bufferedReader.readLine()) != null) {
String[] firstLineNumbers = firstLine.split("\\s+");
System.out.println("First line array length: " + firstLineNumbers.length);
for (int i=0; i<firstLineNumbers.length; i++) {
System.out.println(firstLineNumbers[i]);
}
}
bufferedReader.close();
String numberString = "G H 5 4";
String[] numbers = numberString.split("\\s+");
System.out.println("Numbers array length: " + numbers.length);
for (int i=0; i<numbers.length; i++) {
System.out.println(numbers[i]);
}
} catch(Exception exception) {
System.out.println("IOException occured");
exception.printStackTrace();
}
}
}
The result is:
First line array length: 3
G
H
5 4
Numbers array length: 4
G
H
5
4
Why do the numbers from the file not get parsed the same as the same string defined within code?
Based on feedback I changed the regex to split("[\\s\\h]+") which resolved the issue; the numbers for the file were properly split which clearly indicated that I had a different whitespace-like character in the text file that I was using. I then replaced the contents of the file (using notepad) and reverted back to split("\\s+") and found that it worked correctly this time. So at some point I must have introduced different white-space like characters in the file (maybe a copy/paste issue). In the end the take away is I should use split("[\\s\\h]+") when reading from a file where I want to split on spaces as it will cover more scenarios that may not be immediately obvious.
Thanks to all for helping me find the root cause of my issue.
So I am trying to read values in from a txt file and add them to an ArrayList. I use the following code but immediately after using it the ArrayList is still empty when I use System.out.print(list). Are there any easy to spot mistakes?
ArrayList<Integer> list = new ArrayList<>();
Scanner in = null;
try{
String fname = "p01-runs.txt";
in = new Scanner(new File(fname));
}catch (FileNotFoundException pExcept){
System.out.println("Sorry, the File you tried to open does not exist. Ending program.");
System.exit(-1);
}
while (in.hasNextInt())
{
int x = in.nextInt();
list.add(x);
}
edit: input file is just a txt file with integer values as follows:
2 8 3
2 9
8
6
3 4 6 1 9
A call to hashNextInt() can return false for a number of reasons, including:
there is no more input, or
the next token on the input stream is not a valid integer.
These could be due to an empty input file, or to a mismatch between the file's format and the way you are trying to read it.
In your example, it is also possible that some IOException apart from FileNotFoundException is being thrown.
UPDATE - The problem is something that you are not telling / showing us. Consider this ... using your code and your input file.
[stephen#blackbox tmp]$ cat Test.java
import java.util.*;
import java.io.*;
public class Test {
public static void main(String[] args) {
ArrayList<Integer> list = new ArrayList<>();
Scanner in = null;
try{
String fname = "test.txt";
in = new Scanner(new File(fname));
}catch (FileNotFoundException pExcept){
System.out.println("Sorry, the File you tried to open does not exist. Ending program.");
System.exit(-1);
}
while (in.hasNextInt())
{
int x = in.nextInt();
list.add(x);
}
System.out.println("Read " + list.size() + " numbers");
}
}
[stephen#blackbox tmp]$ cat test.txt
2 8 3
2 9
8
6
3 4 6 1 9
[stephen#blackbox tmp]$ javac Test.java
[stephen#blackbox tmp]$ java Test
Read 12 numbers
[stephen#blackbox tmp]$
Reading only Integers from a text file and storing in an array and display it to user
How can i read only integers from a text file that contains both Integers ans Strings..
Suppose i have a text file like this..
10 10 100 100 Line
10 20 15 30 Rectangle
100 50 50 Circle
10 10 50 50 Line
0 0 0 xyz
We should search each token and if we find some meaningful letter Line,Rectangle,Circle
the integers information of that particular Shape should be stored in an array how is this possible..
Scanner s = new Scanner (new File ("a.txt")).useDelimiter("\\s+");
while (s.hasNext()) {
if (s.hasNextInt()) { // check if next token is an int
System.out.print(s.nextInt()); // display the found integer
} else {
s.next(); // else read the next token
}
}
This will only read the integers on lines that contains the String "Line", "Circle" or "Rectangle".
Scanner s = new Scanner(new File("sample.txt")).useDelimiter("\\n");
while (s.hasNext()) {
String line = s.next();
if(line.matches("^.+(Line|Circle|Rectangle)$")) {
line = line.replaceAll("(Line|Circle|Rectangle)","");
String[] tokens = line.split(" ");
for(String t: tokens) {
System.out.print(t+" ");
}
}
}
The above prints out:
10 10 100 100 10 20 15 30 100 50 50 10 10 50 50
An elegant way is using Antlr
and define your lexer and parser rules.
Otherwise:
BufferedReader reader = new BufferedReader(new FileReader("/path/to/file.txt"));
String line = null;
while ((line = reader.readLine()) != null) {
String[] parts = string.split(" "); // this splits the line by spaces
// ... it is trivial what you should do next
//
}
you can iterate over the tokens of each line
use integer.parseInt(parts[i]) to parse to an Int and catch the exception for a String. This is not very elegant though.
You can use regex instead to match instead.
I have a text file with the following contents (delimiter is a single space):
1231 2134 143 wqfdfv -89 rwq f 8 qer q2
sl;akfj salfj 3 sl 123
My objective is to read the integers and strings seperately. Once I know how to parse them, I will create another output file to save them (but my question is only to know how to parse this text file).
I tried using Scanner and I am NOT able to get beyond the first inetger:
Scanner s = new Scanner (new File ("a.txt")).useDelimiter("");
while (s.hasNext()){
System.out.print(s.nextInt());}
and the output is
1231
How can I also get other integers from both the lines?
My desired outout is:
1231
2134
143
-89
8
3
123
The delimiter should be something else like at least one whitespace or more
Scanner s = new Scanner (new File ("a.txt")).useDelimiter("\\s+");
while (s.hasNext()) {
if (s.hasNextInt()) { // check if next token is an int
System.out.print(s.nextInt()); // display the found integer
} else {
s.next(); // else read the next token
}
}
and i have to admit that the solution from gotuskar is the better one in this simple case.
When reading data from file, read all as string types. Then test whether it is number by parsing it using Integer.parseInt(). If it throws an exception then it is a string, otherwise it is a number.
while (s.hasNext()) {
String str = s.next();
try {
b = Integer.parseInt(str);
} catch (NumberFormatException e) { // only catch specific exception
// its a string, do what you need to do with it here
continue;
}
// its a number
}