Read only one line of Integers from a file - java

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
}

Related

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 to properly read integer from file in 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

Scanner issue with "hasNextInt()"

I have a file that has a different integer on each line. for example:
5
4
3
2
1
I am trying to write a program to run through each int, and put that int into an array. So far, my code is:
Scanner sc = new Scanner(args[0]);
BufferedReader reader = new BufferedReader(new FileReader(args[0]));
lines = 0;
while (reader.readLine() != null) lines++;
reader.close();
intArray = new int[lines];
int counter = 0;
while(sc.hasNextInt()) {
intArray[counter] =sc.nextInt();
counter++;
}
My program creates the array with the right number of indices, but it is never going into the while loop for the scanner. I have no idea why this is, as it looks like I have the same code according to this page.
Unless your file path is space separated numbers, you won't get any numbers. The Scanner was scanning the file path (as a String), not the file.
Scanner sc = new Scanner(new FileInputStream(args[0]));
And FYI, it would be more clear if you used a List rather than reading the file twice.

Reading from a text file in Java

I have a text file like this:
Item 1
Item 2
Item 3
I need to be able to read each "Item X" into a string and ideally store all the strings as a vector / ArrayList.
I tried:
InputStream is = new FileInputStream("file.txt");
is.read(); //looped for every line of text
but that seems to only handle integers.
Thanks
You have several answers here, the easiest would be to us a Scanner (in java.util).
It has several convenience methods like nextLine() and next() and nextInt(), so you could simply do the following:
Scanner scanner = new Scanner(new File("file.txt"));
List<String> text = new ArrayList<String>();
while (scanner.hasNextLine()) {
text.add(scanner.nextLine());
}
Alternatively you could use a BufferedReader (in java.io):
BufferedReader reader = new BufferedReader(new FileReader("file.txt"));
List<String> text = new ArrayList<String>();
for (String line; (line = reader.readLine()) != null; ) {
text.add(line);
}
However Scanners are generally easier to work with.
You should use FileUtils to do this. It has a method named readLines
public static List<String> readLines(File file, Charset encoding) throws IOException
Reads the contents of a file line by line to a List of Strings. The file is always closed.
See #BackSlash's comment above to see how you're using InputStream.read() wrong.
#BackSlash also mentioned you can use java.nio.file.Files#readAllLines but only if you're using Java 1.7 or later.
You could use Java 7's Files#readAllLines. A short one-liner and no 3rd party library imports necessary :)
List<String> lines =
Files.readAllLines(Paths.get("file.txt"), StandardCharsets.UTF_8);
BufferedReader br = new BufferedReader(new FileReader("file.txt"));
try {
StringBuilder sb = new StringBuilder();
String line = br.readLine();
String [] tmp ;
while (line != null) {
sb.append(line);
tmp = line.Split(" ");
line = br.readLine();
}
String everything = sb.toString();
} finally {
br.close();
}
Scanner scan = new Scanner(new FileInputStream("file.txt"));
scan.nextLine();

Reading certain lines only from input?

If i have some code such as input = new BufferedReader(new FileReader(args[0])); And the input file contain pairs of lines, how can I make it so only the first line from each line is imported? So in other words, every odd numbered line only?
Thanks
You might like to consider the use of java.io.LineNumberReader to make the filtering of odd lines (lineNo % 2 == 1) simpler. Or in an alternative approach, if you are using JDK7, you could use the java.nio.files.Files.readAllLines() method and again filter the odd ones upon iteration.
String line = input.readLine();
while (line != null) {
// do something with the line
// Skip every other line
input.readLine();
// Get next line
line = input.readLine();
}
something like this will read in the file and give you every 2nd line in a string buffer.
BufferedReader br = new BufferedReader(new FileReader(args[0]));
String line;
StringBuffer endResult = new StringBuffer(1000);
int lineNumber=1;
while ((line=br.readLine()) != null) {
//every odd line will be added, 1, 3, 5 etc
if (lineNumber++%2==1) {
endResult.append(line+"\n");
}
}

Categories

Resources