How to properly read integer from file in Java - java

I have read previous posts and tryed to integrate code in to my project.
I am trying to read integers from my txt file.
I am using this method:
static Object[] readFile(String fileName) throws FileNotFoundException {
Scanner scanner = new Scanner(new File(fileName));
List<Integer> tall = new ArrayList<Integer>();
while (scanner.hasNextInt()) {
tall.add(scanner.nextInt());
}
return tall.toArray();
}
I don't know the size of data, so i am using List
in main calling method:
Object [] arr = readFile("C:\\02.txt");
System.out.println(arr.length);
I am getting that the array size is 0;
The integers i am trying to read from the file is binary Sequence. (1010101010...)
I thought that the problem is connected with scanner maybe he thinks that it is not the integer.

You can use BufferReader instead :
String line = "";
List<Integer> tall = new ArrayList<Integer>();
try {
BufferedReader br = new BufferedReader(new FileReader(fileName));
while ((line = br.readLine())!= null) {
tall.add(Integer.parseInt(line, 2));
}
br.close();
}catch(IOException e) {}

If you are reading data in binary form then consider using nextInt or hasNextInt with radix.
while (scanner.hasNextInt(2)) {
tall.add(scanner.nextInt(2));
}
Otherwise you will be reading integers as decimals so values may be out of integers range like in case of
11111111111111111111111111111111

Related

Read only one line of Integers from a file

I am trying to read a file which contains integers. The file has 40 lines, each having 80 integers. However when I run the following code, I get 40 lines and 3200 integers in each line (it reads the entire file for each line). How can I fix this.
while(input.hasNextLine()){
++rows;
Scanner colReader = new Scanner(input.nextLine());
while(colReader.hasNextInt()){
++columns;
colReader.nextInt();
}
colReader.close();
}
You can also simplify your code somewhat. You can keep on reading integers one by one.
Scanner input = new Scanner(new File("f:/numbs.txt"));
while (input.hasNextInt()) {
int v = input.nextInt();
System.out.println(v);
}
Because you are duplicated the loop, if you want to read a file, you can do the next
BufferedReader bufferReader = new BufferedReader(new FileReader(new File("")));
int line;
StringBuilder stringBuilder = new StringBuilder();
while ( (line =bufferReader.read()) != 0 ) {
// Do something
}

Why is my program reading one less line than there actually is? And why is my array taking in only ones?

In my high school comp sci class I have to read a text file with marks and then create an array with those marks in them (so I can manipulate them later). When I try and read the number of lines in the program it reads one less than there is, and when I output the array it consists of only "1.00" written to the amount of lines it has counted (which is incorrect).
import java.awt.*;
import java.io.*;
import hsa.Console;
public class Assignment3Q3
{
static Console c;
public static void main (String[] args) throws IOException
{
c = new Console ();
BufferedReader input = new BufferedReader (new FileReader ("marks.txt"));
String mark = input.readLine ();
int lines = 0;
while (input.readLine () != null)
lines++;
input.close ();
c.println (lines);
double[] marks = new double [lines];
int count = 0;
BufferedReader input1 = new BufferedReader (new FileReader ("marks.txt"));
while (input1.readLine () != null)
{
marks [count] = Double.parseDouble (mark);
count += 1;
if (count == lines)
{
break;
}
}
for (int x = 0 ; x < lines ; x++)
{
c.println (marks [x]);
}
}
}
In your second while loop, you are always assigning the parsed version of mark variable to the marks array elements. But you have only set mark variable once in your code, which is the first line of your file.
Anyway without reading the file twice (once to get the number of lines and then to store the actual line content), you can do this in a single read cycle by using a List instead of an array.
try (BufferedReader input = new BufferedReader (new FileReader("src/marks.txt"))) {
List<Double> marks = new ArrayList<>();
String line;
while ((line = input.readLine()) != null) {
marks.add(Double.parseDouble(line));
}
System.out.println(marks);
} catch (IOException e) {
e.printStackTrace();
}
In case you really want to get these marks to an array, you can onvert the above list into an array as follows.
Double[] marksArray = marks.toArray(new Double[marks.size()]);
Also as I have done in the above code snippet, better to use try with resources approach when you create AutoCloseable resources such as BufferedReader or FileReader. Then you don't have to close them explicitly in your code.
Why this separation in two steps at all? This is error prone. No values in the marks-array above the current line-count are accessed. So store the doubles in a dynamicly growing ArrayList<Double> instead and do the job in one step.

Reading data from a file in Java

So I have a background in c++ and I am trying to learn java. Everything is pretty similar. I am having a problem thought with file i/o. So I am messing around and doing really simple programs to get the basic ideas. Here is my code to read data from a file. So I am reading Core Java Volume 1 by Cay Hortsman and it tells me to write this to read from a file,
Scanner in = new Scanner(Paths.get("myFile.txt");
But when I write it in my code, it gives me a red line under paths. So I am not sure how to read from a file. It does not go into much detail about the subject. So my program below I am trying to just read numbers in from a file and store them in an array.
package practice.with.arrays.and.io;
import java.io.IOException;
import java.nio.file.Path;
import java.util.*;
public class PracticeWithArraysAndIO
{
static final int TEN = 10;
public static void main(String[] args) throws IOException
{
//Declaring a scanner object to read in data
Scanner in = new Scanner(Paths.get("myFile.txt"));
//Declaring an array to store the data from the file
int[] arrayOfInts = new int[TEN];
//Local variable to store data in from the file
int data = 0;
try
{
for(int i = 0; i < TEN; i++)
{
data = in.nextInt();
arrayOfInts[i] = data;
}
}
finally
{
in.close();
}
}
It is not clear why you are doing Paths.get(filename)).
You can wrap a Scanner around a file like this. As the comments below mention, you should choose an appropriate charset for your file.
Scanner in = new Scanner(new File("myFile.txt"), StandardCharsets.UTF_8);
To use the constant above, you need the following import, and Java 7.
import java.nio.charset.StandardCharsets
With my experience in Java, I've used the BufferedReader class for reading a text file instead of the Scanner. I usually reserve the Scanner class for user input in a terminal. Perhaps you could try this method out.
Create a BufferedReader with FileReader like so:
BufferedReader buffReader = new BufferedReader(new FileReader("myFile.txt"));
After setting this up, you can read lines with:
stringName = buffReader.readLine();
This example will set the String, stringName, to the first line in your document. To continue reading more lines, you'll need to create a loop.
You need to import java.nio.file.Paths.
I've used the BufferedReader class.
I hope it is helpful for you
public class PracticeWithArraysAndIO {
static final int TEN = 10;
public static void main(String[] args) throws IOException
{
BufferedReader br = null;
try{
br = new BufferedReader(new FileReader("/home/myFile.txt"));//input your file path
int value=0;
int[] arrayOfInts = new int[TEN];
int i=0;
while((value = br.read()) != -1)
{
if(i == 10) //if out of index, break
break;
char c = (char)value; //convert value to char
int number = Character.getNumericValue(c); //convert char to int
arrayOfInts[i] = number; //insert number into array
i++;
}
}catch(IOException e){
e.printStackTrace();
}finally{
if(br != null)
br.close(); //buffer close
}
}
}

Java: Reading txt file into a 2D array

For homework, we have to read in a txt file which contains a map. With the map we are supposed to read in its contents and place them into a two dimensional array.
I've managed to read the file into a one dimensional String ArrayList, but the problem I am having is with converting that into a two dimensional char array.
This is what I have so far in the constructor:
try{
Scanner file=new Scanner (new File(filename));
while(file.hasNextLine()){
ArrayList<String> lines= new ArrayList<String>();
String line= file.nextLine();
lines.add(line);
map=new char[lines.size()][];
}
}
catch (IOException e){
System.out.println("IOException");
}
When I print out the lines.size() it prints out 1 but when I look at the file it has 10.
Thanks in advance.
You have to create the list outside the loop. With your actual implementation, you create a new list for each new line, so it will always have size 1.
// ...
Scanner file = new Scanner(new File(filename));
List<String> lines = new ArrayList<String>(); // <- declare lines as List
while(file.hasNextLine()) {
// ...
BTW - I wouldn't name the char[][] variable map. A Map is a totally different data structure. This is an array, and if you create in inside the loop, then you may encounter the same problems like you have with the list. But now you should know a quick fix ;)
Change the code as following:
public static void main(String[] args) {
char[][] map = null;
try {
Scanner file = new Scanner(new File("textfile.txt"));
ArrayList<String> lines = new ArrayList<String>();
while (file.hasNextLine()) {
String line = file.nextLine();
lines.add(line);
}
map = new char[lines.size()][];
} catch (IOException e) {
System.out.println("IOException");
}
System.out.println(map.length);
}

Text file parsing using java, suggestions needed on which one to use

I can successfully read text file using InputFileStream and Scanner classes. It's very easy but I need to do something more complex than that. A little background about my project first.. I have a device with sensors, and I'm using logger that will log every 10sec data from sensors to a text file. Every 10 sec its a new line of data. So what I want is when I read a file is to grab each separate sensor data into an array. For example:
velocity altitude latitude longitude
22 250 46.123245 122.539283
25 252 46.123422 122.534223
So I need to grab altitude data (250, 252) into an array alt[]; and so forth vel[], lat[], long[]...
Then the last line of the text file will different info, just a single line. It will have the date, distance travelled, timeElapsed..
So after doing a little research I came across InputStream, Reader, StreamTokenizer and Scanner class. My question is which one would you recommend for my case? Is it possible to do what I need to do in my case? and will it be able to check what the last line of the file is so it can grab the date, distance and etc.. Thank you!
Reader + String.split()
String line;
String[] values;
BufferedReader reader = new BufferedReader(new FileReader(args[0]));
List<Integer> velocity = new ArrayList<Integer>();
List<Integer> altitude = new ArrayList<Integer>();
List<Float> latitude = new ArrayList<Float>();
List<Float> longitude = new ArrayList<Float>();
while (null != (line = reader.readLine())) {
values = line.split(" ");
if (4 == values.length) {
velocity.add(Integer.parseInt(values[0]));
altitude.add(Integer.parseInt(values[1]));
latitude.add(Float.parseFloat(values[2]));
longitude.add(Float.parseFloat(values[3]));
} else {
break;
}
}
If you need arrays not list:
velocity.toArray();
As far I undestand data lines has 4 items and last line has 3 items (date, distance, elapsed time)
I would use Scanner. Take a look at the examples here. Another option for you to use BufferedReader to read a line and then have parse method to parse that line into the tokens you want.
Also you might find this thread to be useful.
Very quick code base on the link above. The inputs array has your file data tokens.
public static void main(String[] args) {
BufferedReader in=null;
List<Integer> velocityList = new ArrayList<Integer>();
List<Integer> altitudeList = new ArrayList<Integer>();
List<Double> latitudeList = new ArrayList<Double>();
List<Double> longitudeList = new ArrayList<Double>();
try {
File file = new File("D:\\test.txt");
FileReader reader = new FileReader(file);
in = new BufferedReader(reader);
String string;
String [] inputs;
while ((string = in.readLine()) != null) {
inputs = string.split("\\s");
//here is where we copy the data from the file to the data stucture
if(inputs!=null && inputs.length==4){
velocityList.add(Integer.parseInt(inputs[0]));
altitudeList.add(Integer.parseInt(inputs[1]));
latitudeList.add(Double.parseDouble(inputs[2]));
longitudeList.add(Double.parseDouble(inputs[3]));
}
}
} catch (IOException e) {
e.printStackTrace();
} finally{
try {
if(in!=null){
in.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
//here are the arrays you want!!!
Integer [] velocities = (Integer[]) velocityList.toArray();
Integer [] altitiudes = (Integer[]) altitudeList.toArray();
Double [] longitudes = (Double[]) longitudeList.toArray();
Double [] latitudes = (Double[]) latitudeList.toArray();
}
As your data is relatively simple, BufferedReader and StringTokenizer should do the trick. You'll have to read ahead by one line to detect when there are no more lines left.
Your code could be something like this
BufferedReader reader = new BufferedReader( new FileReader( "your text file" ) );
String line = null;
String previousLine = null;
while ( ( line = reader.readLine() ) != null ) {
if ( previousLine != null ) {
//tokenize and store elements of previousLine
}
previousLine = line;
}
// last line read will be in previousLine at this point so you can process it separately
But how you process the line itself is really up to you, you can use Scanner if you're feeling more comfortable with it.

Categories

Resources