Reputation: 103
I have this code to read numbers (type double) from a text file to a list.
ArrayList listTest = new ArrayList();
try {
FileInputStream fis = new FileInputStream(path);
InputStreamReader isr = new InputStreamReader(fis, "UTF-16");
int c;
while ((c = isr.read()) != -1) {
listTest.add((char) c);
}
System.out.println();
isr.close();
} catch (IOException e) {
System.out.println("There is IOException!");
}
However, the output is look like:
1
1
.
1
4
7
4
2
.
8
1
7
3
5
instead of
11.147
42.81735
How can add the number to list line by line?
Upvotes: 0
Views: 73
Reputation: 1075
As you say that they are doubles, this will convert them to doubles and add them to a list of doubles. This also has the benefit of not adding anything which can't be parsed to a double to your list which gives a bit of data validation.
List<Double> listTest = new ArrayList<Double>();
try (BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(path), "UTF-16"))) {
String line;
while ((line = br.readLine()) != null) {
try {
listTest.add(Double.parseDouble(line));
} catch (NumberFormatException nfe) {
// Not a double!
}
}
System.out.println();
} catch (IOException e) {
System.out.println("There is IOException!");
}
Upvotes: 2
Reputation: 622
In your code, you read the input char by char, that's why you see such an output. You can read the input file using Scanner
in a cleaner way without struggling with the stream readers etc.
ArrayList listTest = new ArrayList();
try {
Scanner scanner = new Scanner(new File(path));
while (scanner.hasNext()) {
listTest.add(scanner.nextLine());
}
scanner.close();
} catch (IOException e) {
System.out.println("There is IOException!");
}
Upvotes: 0
Reputation: 39467
You can wrap the InputStreamReader
in a BufferedReader
which has readLine()
method:
List<String> listTest = new ArrayList<String>();
try (BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(path), "UTF-16"))) {
String line;
while ((line = br.readLine()) != null) {
listTest.add(line);
}
System.out.println(listTest);
} catch (IOException e) {
System.out.println("There is IOException!");
}
Also, notice the try-with-resources
statement which automatically closes the stream (If you are using JDK1.6 or lower, call close()
method in a finally
block). In your sample code, the stream doesn't close if there was an exception.
Upvotes: 1