How to open a txt file and read numbers in Java
Read file, parse each line into an integer and store into a list:
List<Integer> list = new ArrayList<Integer>();
File file = new File("file.txt");
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader(file));
String text = null;
while ((text = reader.readLine()) != null) {
list.add(Integer.parseInt(text));
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (reader != null) {
reader.close();
}
} catch (IOException e) {
}
}
//print out the list
System.out.println(list);
How to read integer values from text file
You might want to do something like this (if you're using java 5 and more)
Scanner scanner = new Scanner(new File("tall.txt"));
int [] tall = new int [100];
int i = 0;
while(scanner.hasNextInt())
{
tall[i++] = scanner.nextInt();
}
Via Julian Grenier from Reading Integers From A File In An Array
Find Integers and float numbers in txt file
You can do it with the following easy steps:
- When you read a line, split it on whitespace and get an array of tokens.
- While processing each token,
- Trim any leading and trailing whitespace and then replace
,
with.
- First check if the token can be parsed into an
int
. If yes, write it intooutInt
(the writer for integers). Otherwise, check if the token can be parsed intofloat
. If yes, write it intooutFloat
(the writer for floats). Otherwise, ignore it.
- Trim any leading and trailing whitespace and then replace
Demo:
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class Main {
public static void main(String[] args) throws FileNotFoundException, IOException {
BufferedReader in = new BufferedReader(new FileReader("t.txt"));
BufferedWriter outInt = new BufferedWriter(new FileWriter("t2.txt"));
BufferedWriter outFloat = new BufferedWriter(new FileWriter("t3.txt"));
String line = "";
while ((line = in.readLine()) != null) {// Read until EOF is reached
// Split the line on whitespace and get an array of tokens
String[] tokens = line.split("\\s+");
// Process each token
for (String s : tokens) {
// Trim any leading and trailing whitespace and then replace , with .
s = s.trim().replace(',', '.');
// First check if the token can be parsed into an int
try {
Integer.parseInt(s);
// If yes, write it into outInt
outInt.write(s + " ");
} catch (NumberFormatException e) {
// Otherwise, check if token can be parsed into float
try {
Float.parseFloat(s);
// If yes, write it into outFloat
outFloat.write(s + " ");
} catch (NumberFormatException ex) {
// Otherwise, ignore it
}
}
}
}
in.close();
outInt.close();
outFloat.close();
}
}
Read Data From Text File And Sum Numbers
You are calling textfile.nextInt() twice in the loop. Try:
static void filereader(Scanner textfile)
{
int i = 0;
int sum = 0;
while(i <= 19)
{
int nextInt = textfile.nextInt();
System.out.println(nextInt);
sum = sum + nextInt;
i++;
}
}
Read one number per line from file Java
Here is a simple example of how to read the coordinates from a file called input.txt
and parse them into integer variables x
and y
:
Stream<String> lines = Files.lines(Paths.get("input.txt"));
lines.forEach(
line -> {
String[] split = line.split(" ");
int x = Integer.parseInt(split[0]);
int y = Integer.parseInt(split[1]);
System.out.println("x = " + x);
System.out.println("y = " + y);
}
);
Or without using Files.lines()
:
BufferedReader reader = new BufferedReader(new FileReader("input.txt"));
String line = reader.readLine();
while (line != null) {
String[] split = line.split(" ");
int x = Integer.parseInt(split[0]);
int y = Integer.parseInt(split[1]);
System.out.println("x = " + x);
System.out.println("y = " + y);
// read next line
line = reader.readLine();
}
reader.close();
Reading only integers from text file and adding them
You are almost there. Make a sum
to add up the numbers, and add continue
to skip to the next line on error:
int sum = 0;
boolean isGood = true;
for(String str : words) {
try {
sum += Integer.parseInt(str);
} catch (NumberFormatException nfe) {
// If any of the items fails to parse, skip the entire line
isGood = false;
continue;
};
}
if (isGood) {
// If everything parsed, print the sum
System.out.println(sum);
}
Java - How to read a text file with Int's and Strings in the same line
Try something like this:
String line = "";
String[] tokens;
int number;
String name;
while((line = reader.readLine()) != null)
{
tokens = line.split(" ");
// Use the following if you would rather split on whitespace for tab separated data
// tokens = line.split("\\s+");
number = Integer.parseInt(tokens[0]);
name = tokens[1];
System.out.println("Fruit number " + number + " is a " + name + "."
}
Read up on the String.split()
method.
Reading a plain text file in Java
ASCII is a TEXT file so you would use Readers
for reading. Java also supports reading from a binary file using InputStreams
. If the files being read are huge then you would want to use a BufferedReader
on top of a FileReader
to improve read performance.
Go through this article on how to use a Reader
I'd also recommend you download and read this wonderful (yet free) book called Thinking In Java
In Java 7:
new String(Files.readAllBytes(...))
(docs)
or
Files.readAllLines(...)
(docs)
In Java 8:
Files.lines(..).forEach(...)
(docs)
Related Topics
How Do Java Method Annotations Work in Conjunction with Method Overriding
Why Is My Jlabel Not Showing Up
Using Sha1 and Rsa with Java.Security.Signature VS. Messagedigest and Cipher
Java Sorting Based on Enum Constants
How to Copy Hashmap (Not Shallow Copy) in Java
Java's Virtual MAChine's Endianness
When and How Are Classes Garbage Collected in Java
Find the Most Popular Element in Int[] Array
Arrays.Fill with Multidimensional Array in Java
How to Do Query Auto-Completion/Suggestions in Lucene
Is There Any Good and Free Date and Time Picker Available for Java Swing
How to Make a Countdown Timer in Java
How to Use a Java8 Lambda to Sort a Stream in Reverse Order