How to read a file in Java and save each item - java

I have a text file with integers and double number like this:
16 -122.454803 41.923870
17 -122.440536 41.946377
18 -122.440498 41.956013
I have 3 lists(one int and two double lists) and i want to save the items from each column. How can i split the items and save them in the lists?
ArrayList<Integer> list1 = new ArrayList<Integer>();
ArrayList<Double> list2 = new ArrayList<Double>();
ArrayList<Double> list3 = new ArrayList<Double>();
BufferedReader in = new BufferedReader(new FileReader("Nodes.txt"));
String line;
while((line = in.readLine()) != null){
list1.setNodeId(line.split(" "));
System.out.println(line);
}
in.close();

One way to process the data:
String line;
while ((line = reader.readLine()) != null) {
String[] parts = line.split(" ");
if (parts.length != 3) {
continue;
}
list1.add(Integer.parseInt(parts[0]));
list2.add(Double.parseDouble(parts[1]));
list3.add(Double.parseDouble(parts[2]));
}
However: this code lacks error checking on the data type. And I guess you need to process the data afterwards, so I highly suggest that you write a GeoPosition class (just a name guess from the data) with the index and position fields and a parse(String) method to parse each line. A list of such elements is much easier to process afterwards in comparison to 3 separate lists.

You can do something like this:
public static void main(String[] args) {
// TODO Auto-generated method stub
ArrayList<Integer> list1 = new ArrayList<Integer>();
ArrayList<Double> list2 = new ArrayList<Double>();
ArrayList<Double> list3 = new ArrayList<Double>();
BufferedReader in;
String line;
try {
in = new BufferedReader(new FileReader("Nodes.txt"));
while((line = in.readLine()) != null){
System.out.println(line);
String arr[] = line.split(" ");
list1.add(Integer.valueOf(arr[0]));
list2.add(Double.valueOf(arr[1]));
list3.add(Double.valueOf(arr[2]));
}
in.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
for (int i = 0; i < list1.size(); i++){
System.out.println(list1.get(i));
}
for (int i = 0; i < list2.size(); i++){
System.out.println(list2.get(i));
}
for (int i = 0; i < list3.size(); i++){
System.out.println(list3.get(i));
}
}

String.split returns an array of Strings. You need to take appropriate array entry and convert it to desired value type
String[] entries = line.split(" ");
list1.add(Integer.valueOf(entries[0]));
list2.add(Double.valueOf(entries[1]));
list3.add(Double.valueOf(entries[2]));

You can try by this way ;)
ArrayList<Integer> list1 = new ArrayList<Integer>();
ArrayList<Double> list2 = new ArrayList<Double>();
ArrayList<Double> list3 = new ArrayList<Double>();
Path path = Paths.get("C:/User/.../.../.../nodes.txt");
Scanner in = new Scanner(path);
double line;
while(in.hasNextDouble()){
line = in.nextDouble();
list1.add((int)line);
line = in.nextDouble();
list2.add(line);
line = in.nextDouble();
list3.add(line);
System.out.println(line);
}
in.close();
Don't forget to write the correct path, and tell if it's working ;)
edit : be careful, i tried and "15.05" is not working with my method, it needs "15,05", i think it will be the same with the post just over mine

Related

Parsing text file to jagged array

I have the following file
3
2,3,4,5
6,7,8
9,10
and I am trying to convert it to pass it as jagged array of double. By that I mean, I am trying to store this as
double[][] myArray = {{2,3,4},{6,7},{9}}
double[] secondArray = {5,8,10}
I have been able to get the values read from the file but I am stuck on 2 things.
How can I convert the values into double array?
How can I store the last elements into a new array?
I am facing the error because my array contains comma separated values but how can I get the individual values to convert to double? I am still new to Java so I am not aware of all the inbuilt methods.
here is what I have so far
public double[] fileParser(String filename) {
File textFile = new File(filename);
String firstLine = null;
String secondLine = null;
String[] secondLineTokens = null;
FileInputStream fstream = null;
try {
fstream = new FileInputStream(filename);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
BufferedReader br = new BufferedReader(new InputStreamReader(fstream));
try {
firstLine = br.readLine(); // reads the first line
List<String> myList = new ArrayList<String>();
while((secondLine = br.readLine()) != null){
myList.add(secondLine);
//secondLineTokens = secondLine.split(",");
}
String[] linesArray = myList.toArray(new String[myList.size()]);
for(int i = 0; i<linesArray.length; i++){
System.out.println("tokens are: " + linesArray[i]);
}
double[] arrDouble = new double[linesArray.length];
for(int i=0; i<linesArray.length; i++)
{
arrDouble[i] = Double.parseDouble(linesArray[i]); #error here
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
It looks like the first line gives you the number of lines in the rest of the file. You can leverage it to make the arrays upfront, like this:
int n = Integer.parseInt(br.readLine());
double a[][] = new double[n][];
double b[] = new double[n];
for (int i = 0 ; i != n ; i++) {
String[] tok = br.readLine().split(",");
a[i] = new double[tok.length-1];
for (int j = 0 ; j != a[i].length ; j++) {
a[i][j] = Double.parseDouble(tok[j]);
}
b[i] = Double.parseDouble(tok[tok.length-1]);
}
Similarly, you can use String.split method to find out how many entries is to be added to the jagged array. This way the code becomes much shorter, because you can pre-allocate all your arrays.
Demo.

Txt file into a double 2d array

I am trying to read a txt file into a array of doubles. I am using the following code which reads every line of the file:
String fileName="myFile.txt";
try{
//Create object of FileReader
FileReader inputFile = new FileReader(fileName);
//Instantiate the BufferedReader Class
BufferedReader bufferReader = new BufferedReader(inputFile);
//Variable to hold the one line data
String line;
// Read file line by line and print on the console
while ((line = bufferReader.readLine()) != null) {
System.out.println(line);
}
//Close the buffer reader
bufferReader.close();
}catch(Exception e){
System.out.println("Error while reading file line by line:"
+ e.getMessage());
}
However I want to store the txt file into a 2d double array.
I ve tried the above to load also the dimension of the txt. But I am having problems with the exceptions catch (NoSuchElementException e), it seems that it couldnt read the file.
try {
while (input.hasNext()) {
count++;
if (count == 1) {
row = input.nextInt();
r = row;
System.out.println(row);
continue;
} else if (count == 2) {
col = input.nextInt();
System.out.println(col);
c = col;
continue;
} else {
output_matrix = new double[row][col];
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++) {
String el = input.next();
Double temp = Double.valueOf(el);
double number = temp.doubleValue();
//output_matrix[i][j] = el;
output_matrix[i][j] = number;
//System.out.print(output_matrix[i][j]+" ");
}
//System.out.println();
}
}
}
} catch (NoSuchElementException e) {
System.err.println("Sfalma kata ti tropopoisisi toy arxeioy");
System.err.println(e.getMessage()); //emfanisi tou minimatos sfalmatos
input.close();
System.exit(0);
} catch (IllegalStateException e) {
System.err.println("Sfalma kata ti anagnosi toy arxeioy");
System.exit(0);
}
You might want to be using the Scanner class for it, especially the Scanner.nextDouble() method.
Also, if you don't know in advance the dimensions of the array - I'd suggest using an ArrayList instead of a regular array.
Code example:
ArrayList<ArrayList<Double>> list = new ArrayList<>();
while ((line = bufferReader.readLine()) != null) {
ArrayList<Double> curr = new ArrayList<>();
Scanner sc = new Scanner(line);
while (sc.hasNextDouble()) {
curr.add(sc.nextDouble());
}
list.add(curr);
}
At firs declare a list and collect into it all read lines:
List<String> tempHistory = new ArrayList<>();
while ((line = bufferReader.readLine()) != null) {
tempHistory.add(line);
}
Then, after bufferReader.close(); convert this tempHistory list into double[][] array.
double[][] array = new double[tempHistory.size()][];
for (int i = 0; i < tempHistory.size(); i++) {
final String currentString = tempHistory.get(i);
final String[] split = currentString.split(" ");
array[i] = new double[split.length];
for (int j = 0; j < split.length; j++) {
array[i][j] = Double.parseDouble(split[j]);
}
}
It works, but as I added in comments, this is a not so good solution, and is better to use Collections instead of array.
BTW, it works even the rows lengths are different for different lines.

How to read a file and store it in array in java

I want to read a text file and store it as string multidimensional array in java.
The input will be like this
11 12 13
12 11 16
33 45 6
I want to store this in
String[][] as={{"11","12","13"},
{"12","11","16"},
{"33","45"}};
My code
String file="e:\\s.txt";
try
{
int counterCol=0,counterRow=0;
String[][] d=null;
BufferedReader bw=new BufferedReader(new FileReader(file));
String str=bw.readLine();
String[] words=str.split(",");
System.out.println(words.length+"Counterrow");
counterCol=words.length; //get total words split by comma : column
while(bw.readLine()!=null)
{
counterRow++;
// to get the total words as it gives total row count
}
String[][] d=new String[counterRow][counterCol];
for(int x=0;x<counterRow;x++)
{
for(int y=0;y<counterCol;y++)
{
d[x][y]=bw.readLine();
//storing in array. But here gives me the exception
}
}
But I cannot store it in array as I getting null pointer exception. How to over come this problem
Quite a few things wrong here:
Array not initialized
You are not looping over the file lines using the BufferedReader
You are splitting by comma instead of space as specified in your sample data
Using Java Collections will help you here. Specifically ArrayList.
Give something like this a go:
String file="e:\\s.txt";
try {
int counterRow = 0;
String[][] d = new String[1][1];
BufferedReader bw = new BufferedReader(new FileReader(file));
List<List<String>> stringListList = new ArrayList<List<String>>();
String currentLine;
while ((currentLine = bw.readLine()) != null) {
if (currentLine != null) {
String[] words = currentLine.split(" ");
stringListList.add(Arrays.asList(words));
}
}
// Now convert stringListList into your array if needed
d = Arrays.copyOf(d, stringListList.size());
for (List<String> stringList : stringListList) {
String[] newArray = new String[stringList.size()];
for (int i = 0; i < stringList.size(); i++) {
newArray[i] = stringList.get(i);
}
d[counterRow] = newArray;
counterRow ++;
}
} catch (Exception e) {
// Handle exception
}
You get NullPointer because your array 'd' is null:
String[][] d=null;
Initialize it and it should be work:
String[][] d= new String [counterCol][counterRow];

Values Not Being Read in Correctly From File

I am trying to read in x,y coordinates in from a file separated by a comma. However, the elements are not being added to the ArrayList properly. Where am I going wrong here?
ArrayList<Double> xpointArrayList = new ArrayList<Double>();
ArrayList<Double> ypointArrayList = new ArrayList<Double>();
try {
BufferedReader input = new BufferedReader(new FileReader(args[0]));
String line;
while ((line = input.readLine()) != null) {
line = input.readLine();
String[] splitLine = line.split(",");
double xValue = Double.parseDouble(splitLine[0]);
double yValue = Double.parseDouble(splitLine[1]);
xpointArrayList.add(xValue);
ypointArrayList.add(yValue);
}
input.close();
} catch (IOException e) {
} catch (NullPointerException npe) {
}
double[] xpoints = new double[xpointArrayList.size()];
for (int i = 0; i < xpoints.length; i++) {
xpoints[i] = xpointArrayList.get(i);
}
double[] ypoints = new double[ypointArrayList.size()];
for (int i = 0; i < ypoints.length; i++) {
ypoints[i] = ypointArrayList.get(i);
}
When I do the Array.toSring call on the xpoints and the ypoints array. It only has one number. For example in the file:
1,2
3,4
0,5
It only has 3.0 for the xpoints array and 4.0 for the ypoints array. Where is it going wrong?
while ((line = input.readLine()) != null) {
line = input.readLine();
You just read a line, discarded it, then read another line.
Rinse, repeat (since it's a loop).
In the future, you really should think about using the debugger. You can step through your code as it executes and see exactly what is going on. Learning to use it will be invaluable.
Edit To add: As GregHaskins points out the comments below, you also obscured the problem by catching the NullPointerException and not acting on it. On the second iteration of your loop, line would be null on the second call to readLine() because there was nothing left in the file. The call to split() then throws a NullPointerException which you catch ... then silently ignore.
You can also read input using the Scanner class. The following is a modified version of your code using the Scanner and File classes to read the File:
ArrayList<Double> xpointArrayList = new ArrayList<Double>();
ArrayList<Double> ypointArrayList = new ArrayList<Double>();
try {
Scanner input = new Scanner(new File("testing.txt"));
String line;
while (input.hasNextLine()) {
line = input.nextLine();
String[] splitLine = line.split(",");
double xValue = Double.parseDouble(splitLine[0]);
double yValue = Double.parseDouble(splitLine[1]);
xpointArrayList.add(xValue);
ypointArrayList.add(yValue);
}
input.close();
} catch (IOException e) {
} catch (NullPointerException npe) {
}
double[] xpoints = new double[xpointArrayList.size()];
for (int i = 0; i < xpoints.length; i++) {
xpoints[i] = xpointArrayList.get(i);
}
double[] ypoints = new double[ypointArrayList.size()];
for (int i = 0; i < ypoints.length; i++) {
ypoints[i] = ypointArrayList.get(i);
}
Your reading style is not right. You are calling the readLine() two times. One at the top and other just after entering the while() loop. This way u are not processing all the points. Some point coordinates are getting ignored.
You should use.
while ((line = input.readLine()) != null) {
//line = input.readLine(); */Remove this */
*/your code */
}

convert String to Array in Java

I have a txt file like this:
5
1
3
6
9
I want to read them using java and store all of the numbers into a array.How do I do that? read them in as string and convert to arrray? (how to convert?)
the file only contain ints.
I tried read them into a string
and use this to convert
static public int[] strToA(String str)
{
int len = str.length();
int[] array = new int[len];
for (int i = 0; i < len; i++)
{
array[i] = Integer.parseInt(str.substring(i,i+1));
}
return array;
}
Scanner can help you read your file, and you can use a List or something else to store the info.
After that, you can use this List to convert your Array.
public static Integer[] read2array(String filePath) throws IOException {
List<Integer> result = new ArrayList<Integer>();
RandomAccessFile randomAccessFile = new RandomAccessFile(filePath, "r");
String line = null;
while(null != (line = randomAccessFile.readLine())) {
result.add(new Integer(line));
}
randomAccessFile.close();
return result.toArray(new Integer[result.size()]);
}
Code would be something like this. This is untested code and may have Syntax errors.
Path file = "yourfile";
// open file
try (InputStream in = Files.newInputStream(file);
BufferedReader reader =
new BufferedReader(new InputStreamReader(in))) {
String line = null;
intArr = new int[10]; // bad code could fail if file has more than 10
int i = 0;
while ((line = reader.readLine()) != null) {
intArr[i++] = Integer.parseInt(line); // parse String to int
}
} catch (IOException x) {
System.err.println(x);
}
To use List instead of array change line
intArr = new int[10];
to
List intArr = new ArrayList();
Code would be something like
List intArr = new ArrayList();
while ((line = reader.readLine()) != null) {
intArr.add(Integer.parseInt(line)); // parse String to int
}

Categories

Resources