How to open a txt file and read numbers in Java - java

How can I open a .txt file and read numbers separated by enters or spaces into an array list?

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);

A much shorter alternative is below:
Path filePath = Paths.get("file.txt");
Scanner scanner = new Scanner(filePath);
List<Integer> integers = new ArrayList<>();
while (scanner.hasNext()) {
if (scanner.hasNextInt()) {
integers.add(scanner.nextInt());
} else {
scanner.next();
}
}
A Scanner breaks its input into tokens using a delimiter pattern, which by default matches whitespace. Although default delimiter is whitespace, it successfully found all integers separated by new line character.

Good news in Java 8 we can do it in one line:
List<Integer> ints = Files.lines(Paths.get(fileName))
.map(Integer::parseInt)
.collect(Collectors.toList());

try{
BufferedReader br = new BufferedReader(new FileReader("textfile.txt"));
String strLine;
//Read File Line By Line
while ((strLine = br.readLine()) != null) {
// Print the content on the console
System.out.println (strLine);
}
//Close the input stream
in.close();
}catch (Exception e){//Catch exception if any
System.err.println("Error: " + e.getMessage());
}finally{
in.close();
}
This will read line by line,
If your no. are saperated by newline char. then in place of
System.out.println (strLine);
You can have
try{
int i = Integer.parseInt(strLine);
}catch(NumberFormatException npe){
//do something
}
If it is separated by spaces then
try{
String noInStringArr[] = strLine.split(" ");
//then you can parse it to Int as above
}catch(NumberFormatException npe){
//do something
}

File file = new File("file.txt");
Scanner scanner = new Scanner(file);
List<Integer> integers = new ArrayList<>();
while (scanner.hasNext()) {
if (scanner.hasNextInt()) {
integers.add(scanner.nextInt());
}
else {
scanner.next();
}
}
System.out.println(integers);

import java.io.*;
public class DataStreamExample {
public static void main(String args[]){
try{
FileWriter fin=new FileWriter("testout.txt");
BufferedWriter d = new BufferedWriter(fin);
int a[] = new int[3];
a[0]=1;
a[1]=22;
a[2]=3;
String s="";
for(int i=0;i<3;i++)
{
s=Integer.toString(a[i]);
d.write(s);
d.newLine();
}
System.out.println("Success");
d.close();
fin.close();
FileReader in=new FileReader("testout.txt");
BufferedReader br=new BufferedReader(in);
String i="";
int sum=0;
while ((i=br.readLine())!= null)
{
sum += Integer.parseInt(i);
}
System.out.println(sum);
}catch(Exception e){System.out.println(e);}
}
}
OUTPUT::
Success
26
Also, I used array to make it simple.... you can directly take integer input and convert it into string and send it to file.
input-convert-Write-Process... its that simple.

Related

Find a word and return specific value of the word

I have a file with this content:
1.10.100.1 1000.0
1.10.100.2 2000.0
1.10.100.3 2000.0
1.10.500.4 1000.0
i wrote the function that find the specific string in the file:
public double searchInBalance(String depositNumber) {
try {
String[] words = null;
FileReader fileReader = new FileReader(file);
BufferedReader bufferedReader = new BufferedReader(fileReader);
String string;
String inputBalanceToFind = depositNumber;
while ((string = bufferedReader.readLine()) != null) {
words = string.split(" ");
for (String word : words) {
if (word.equals(inputBalanceToFind)) {
System.out.println("string :" + string);
}
}
}
fileReader.close();
} catch (Exception e) {
e.printStackTrace();
System.out.println("Error in searchInBalance");
}
return 1;
}
i want to make a function that when find the left value of the file return the right value(the double value) back but have no idea how to do that please help me
public double searchInBalance(String depositNumber){
try {
String[] words = null;
FileReader fileReader = new FileReader(file);
BufferedReader bufferedReader = new BufferedReader(fileReader);
String string;
String inputBalanceToFind = depositNumber;
while ((string = bufferedReader.readLine()) != null) {
words = string.split(" ");
for (int i = 1; i < words.length; i += 2) {
if (words[i].equals(inputBalanceToFind)) {
System.out.println(words[i]+" - "+words[i - 1]);
}
}
}
fileReader.close();
} catch (Exception e) {
e.printStackTrace();
System.out.println("Error in searchInBalance");
}
}
Just make a for loop with a counter to work with the indexes of the Array. But this is not a good programming style and you should try to improve your solution :D

String cannot be converted to array

I have a program that reads in a file using a filename specified by the user.
All file contents must be read and stored in the array. I seem to have done the IO Correctly besides this error. I understand what the error is but not sure how to correct.
EDIT: The array is already defined in the file.
Zoo.java:284: error: incompatible types: String cannot be converted to
Animals
animals[ j ] = bufferedReader.readLine();
Here is my code for the readFile Submodule:
public String readFile(Animals[] animals)
{
Scanner sc = new Scanner(System.in);
String nameOfFile, stringLine;
FileInputStream fileStream = null;
BufferedReader bufferedReader;
InputStreamReader reader;
System.out.println("Please enter the filename to be read from.");
nameOfFile = sc.nextLine();
try
{
constructed = true;
fileStream = new FileInputStream(nameOfFile);
bufferedReader = new BufferedReader(new InputStreamReader(fileStream));
while((stringLine = bufferedReader.readLine()) != null)
{
for(int j = 0; j < animals.length; j++)
{
animals[j] = bufferedReader.readLine();
}
}
fileStream.close();
}
catch(IOException e)
{
if(fileStream != null)
{
try
{
fileStream.close();
}
catch(IOException ex2)
{
}
}
System.out.println("Error in file processing: " + e.getMessage();
}
}
Thanks for the help.
animals is array of Animals, but bufferedReader.readLine() reads line. You should convert it to Animal. I don't see definition of your class Animals, but, I think, there should be constructor that takes String as argument.
So, If i'm right, you should basically write:
animals[j] = new Animals(bufferedReader.readLine());
Lots of problems in your code. Starting with the method's input. Also reading from file.
public static void main(String[] args) {
// TODO code application logic here
for(String entry : readFile())
{
System.out.println(entry);
}
}
static public String[] readFile()
{
Scanner sc = new Scanner(System.in);
InputStreamReader reader;
System.out.println("Please enter the filename to be read from.");
String nameOfFile = sc.nextLine();
try(BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(new FileInputStream(nameOfFile))); )
{
//constructed = true; why?
String stringLine;
ArrayList<String> arraylist = new ArrayList();
while((stringLine = bufferedReader.readLine()) != null)
{
arraylist.add(stringLine);
}
return arraylist.toArray(new String[0]);
}
catch (FileNotFoundException ex)
{
Logger.getLogger(Filetoarray.class.getName()).log(Level.SEVERE, null, ex);
}
catch (IOException ex)
{
Logger.getLogger(Filetoarray.class.getName()).log(Level.SEVERE, null, ex);
}
return null;
}

Write to a specific line in a txt document java

I know that there are already some posts about this problem but I don't understand them.
My problem is that I want to find a line in a txt document with a name and I then want to change the next line to the content of a string.
This is what I tried:
public void saveDocument(String name) {
String documentToSave = textArea1.getText();
File file = new File("documents.txt");
Scanner scanner;
BufferedWriter bw;
try {
scanner = new Scanner(file);
bw = new BufferedWriter(new FileWriter(file));
while(scanner.hasNextLine()) {
if(scanner.nextLine().equals(name)) {
if(scanner.hasNextLine()) bw.write(scanner.nextLine() + "\n");
bw.write(documentToSave + "\n");
if(scanner.hasNextLine()) scanner.nextLine();
}
if(scanner.hasNextLine()) bw.write(scanner.nextLine() + "\n");
}
bw.flush();
bw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
May be you try it this way: read your file and keep each line in a list of strings and if you find the name you are looking for replace the next line you read. And then write the strings from that list back to your file. Example:
public class NewClass {
public static void main(String[] args) {
List<String> list = new ArrayList<String>();
list = readFile("uzochi");
writeToFile(list);
}
public static List<String> readFile(String name){
List<String> list = new ArrayList<String>();
try {
FileReader reader = new FileReader("C:\\users\\uzochi\\desktop\\txt.txt");
BufferedReader bufferedReader = new BufferedReader(reader);
String line;
boolean nameFound = false;
while ((line = bufferedReader.readLine()) != null) {
if(line.equalsIgnoreCase(name)){
nameFound = true;
System.out.println("searched name: "+line);
}
if(nameFound){
list.add(line);
line = bufferedReader.readLine();
System.out.println("line to replace: " + line);
line = "another string";
System.out.println("replaced line: "+line);
list.add(line);
nameFound = false;
}
else{
list.add(line);
}
}
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
return list;
}
public static void writeToFile(List<String> list){
try {
FileWriter writer = new FileWriter("C:\\users\\uzochi\\desktop\\txt.txt", false);
BufferedWriter bufferedWriter = new BufferedWriter(writer);
for(String s: list){
bufferedWriter.write(s);
bufferedWriter.newLine();
}
bufferedWriter.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
txt.txt
hallo
hello
hola
uzochi
world
java
print
This code should read the entire file and replace the line with the name.
while(scanner.hasNextLine()) {
String line = scanner.nextLine();
if(line.equals(name)) {
bw.write(documentToSave + "\n");
} else {
bw.write(line + "\n");
}
}
This program will replace the line after a given line. It needs some more work from us, for example if we can define expected i/o and usage. Now it reads from a file and reeplaces a line, but maybe you want to use the line number instead of the line contents to mark which line to replace.
import java.io.*;
public class FileLineReplace {
public static void replaceSelected(String replaceWith, String type) {
try {
String input2 = "";
boolean replace = false;
String input = "";
try (BufferedReader br = new BufferedReader(new FileReader("data.txt"))) {
for (String line;
(line = br.readLine()) != null;) {
// process the line.
System.out.println(line); // check that it's inputted right
if (replace) {
line = "*** REPLACED ***";
replace = false;
}
if (line.indexOf("replaceNextLine") > -1) {
replace = true;
}
input2 = input2 += (line + "\n");
}
// line is not visible here.
}
// check if the new input is right
System.out.println("----------------------------------" + '\n' + input2);
// write the new String with the replaced line OVER the same file
FileOutputStream fileOut = new FileOutputStream("data.txt");
fileOut.write(input2.getBytes());
fileOut.close();
} catch (Exception e) {
System.out.println("Problem reading file.");
e.printStackTrace();
}
}
public static void main(String[] args) {
replaceSelected("1 adam 20 M", "foobar");
}
}
If you run the code, it will replace next line after a line which is "replaceNextLine":
$ java FileLineReplace
asd
zxc
xcv
replaceNextLine
wer
qwe
----------------------------------
asd
zxc
xcv
replaceNextLine
*** REPLACED ***
qwe
My test file is (was)
asd
zxc
xcv
replaceNextLine
wer
qwe
After I run the program, the file looks like this and the line after the specified line is replaced.
asd
zxc
xcv
replaceNextLine
*** REPLACED ***
qwe

Put .txt file data in array

I'm new at java I would like to know how to read a .txt file and then put every single line in an array cell.
.txt file must be formatted as shown:
car //goes in array[0]
boat //goes in array[1]
ship //goes in array[2]
airplane //goes in array[3]
//...and so on..
I've already tried to create a ReadFile class implemented in this way:
import java.io.*;
import java.util.*;
public class ReadFile {
private Scanner x;
public void open(){
try{
x = new Scanner(new File("time_table_data.txt"));
}catch(Exception e){
System.out.println("Could Not Create The File");
}
}
public String read(){
String s = "";
while(x.hasNext()){
String a = x.next();
s = a.format("%s\n",a);
}
return s;
}
public void close(){
x.close();
}
}
The problem is that you don't know how many words there are coming. To solve that, you could use an ArrayList.
List<String> entries = new ArrayList<String>();
while (scanner.hasNext())
{
entries.add(scanner.nextLine());
}
System.out.println(entries);
Access them using the get(int index) method:
String test = entries.get(0); // This will be "car"
if you're willing to use Apache Commons IO then you can do this really easy:
import org.apache.commons.io.FileUtils;
String[] linesArr = new String[0];
List<String> lines = FileUtils.readLines(new File("FILE_NAME.txt"));
if (lines != null) {
linesArr = lines.toArray(linesArr);
}
Just do:
List<String> lines = new ArrayList<String>();
try (BufferedReader br = new BufferedReader(new FileReader(file))) {
String line;
while ((line = br.readLine()) != null) {
lines.add(line); // Add line to list
}
} // Try-with-resources closes reader
You don't need the scanner or anything else fancy when you just looking for whole lines.
If you really need an array not a list at the end you can just read out the array from the final List.
Make a method that reads all data from file and stores in a List as follows.
public ArrayList<String> fileRead(String fileName){
File f;
String s;
FileReader fr = null;
BufferedReader br = null;
ArrayList<String> sl = new ArrayList<String>();
try {
f = new File(fileName);
fr = new FileReader(f);
br = new BufferedReader(fr);
while((s=br.readLine())!=null){
sl.add(s);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally{
try {
if(br!=null)
br.close();
if(fr!=null)
fr.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sl;
}

Read data from a text file using Java

I need to read a text file line by line using Java. I use available() method of FileInputStream to check and loop over the file. But while reading, the loop terminates after the line before the last one. i.e., if the file has 10 lines, the loop reads only the first 9 lines.
Snippet used :
while(fis.available() > 0)
{
char c = (char)fis.read();
.....
.....
}
You should not use available(). It gives no guarantees what so ever. From the API docs of available():
Returns an estimate of the number of bytes that can be read (or skipped over) from this input stream without blocking by the next invocation of a method for this input stream.
You would probably want to use something like
try {
BufferedReader in = new BufferedReader(new FileReader("infilename"));
String str;
while ((str = in.readLine()) != null)
process(str);
in.close();
} catch (IOException e) {
}
(taken from http://www.exampledepot.com/egs/java.io/ReadLinesFromFile.html)
How about using Scanner? I think using Scanner is easier
private static void readFile(String fileName) {
try {
File file = new File(fileName);
Scanner scanner = new Scanner(file);
while (scanner.hasNextLine()) {
System.out.println(scanner.nextLine());
}
scanner.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
Read more about Java IO here
If you want to read line-by-line, use a BufferedReader. It has a readLine() method which returns the line as a String, or null if the end of the file has been reached. So you can do something like:
BufferedReader reader = new BufferedReader(new InputStreamReader(fis));
String line;
while ((line = reader.readLine()) != null) {
// Do something with line
}
(Note that this code doesn't handle exceptions or close the stream, etc)
String file = "/path/to/your/file.txt";
try {
BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(file)));
String line;
// Uncomment the line below if you want to skip the fist line (e.g if headers)
// line = br.readLine();
while ((line = br.readLine()) != null) {
// do something with line
}
br.close();
} catch (IOException e) {
System.out.println("ERROR: unable to read file " + file);
e.printStackTrace();
}
You can try FileUtils from org.apache.commons.io.FileUtils, try downloading jar from here
and you can use the following method:
FileUtils.readFileToString("yourFileName");
Hope it helps you..
The reason your code skipped the last line was because you put fis.available() > 0 instead of fis.available() >= 0
In Java 8 you could easily turn your text file into a List of Strings with streams by using Files.lines and collect:
private List<String> loadFile() {
URI uri = null;
try {
uri = ClassLoader.getSystemResource("example.txt").toURI();
} catch (URISyntaxException e) {
LOGGER.error("Failed to load file.", e);
}
List<String> list = null;
try (Stream<String> lines = Files.lines(Paths.get(uri))) {
list = lines.collect(Collectors.toList());
} catch (IOException e) {
LOGGER.error("Failed to load file.", e);
}
return list;
}
//The way that I read integer numbers from a file is...
import java.util.*;
import java.io.*;
public class Practice
{
public static void main(String [] args) throws IOException
{
Scanner input = new Scanner(new File("cards.txt"));
int times = input.nextInt();
for(int i = 0; i < times; i++)
{
int numbersFromFile = input.nextInt();
System.out.println(numbersFromFile);
}
}
}
Try this just a little search in Google
import java.io.*;
class FileRead
{
public static void main(String args[])
{
try{
// Open the file that is the first
// command line parameter
FileInputStream fstream = new FileInputStream("textfile.txt");
// Get the object of DataInputStream
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine;
//Read File Line By Line
while ((strLine = br.readLine()) != null) {
// Print the content on the console
System.out.println (strLine);
}
//Close the input stream
in.close();
}catch (Exception e){//Catch exception if any
System.err.println("Error: " + e.getMessage());
}
}
}
Try using java.io.BufferedReader like this.
java.io.BufferedReader br = new java.io.BufferedReader(new java.io.InputStreamReader(new java.io.FileInputStream(fileName)));
String line = null;
while ((line = br.readLine()) != null){
//Process the line
}
br.close();
Yes, buffering should be used for better performance.
Use BufferedReader OR byte[] to store your temp data.
thanks.
user scanner it should work
Scanner scanner = new Scanner(file);
while (scanner.hasNextLine()) {
System.out.println(scanner.nextLine());
}
scanner.close();
public class ReadFileUsingFileInputStream {
/**
* #param args
*/
static int ch;
public static void main(String[] args) {
File file = new File("C://text.txt");
StringBuffer stringBuffer = new StringBuffer("");
try {
FileInputStream fileInputStream = new FileInputStream(file);
try {
while((ch = fileInputStream.read())!= -1){
stringBuffer.append((char)ch);
}
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("File contents :");
System.out.println(stringBuffer);
}
}
public class FilesStrings {
public static void main(String[] args) throws FileNotFoundException, IOException {
FileInputStream fis = new FileInputStream("input.txt");
InputStreamReader input = new InputStreamReader(fis);
BufferedReader br = new BufferedReader(input);
String data;
String result = new String();
while ((data = br.readLine()) != null) {
result = result.concat(data + " ");
}
System.out.println(result);
File file = new File("Path");
FileReader reader = new FileReader(file);
while((ch=reader.read())!=-1)
{
System.out.print((char)ch);
}
This worked for me
Simple code for reading file in JAVA:
import java.io.*;
class ReadData
{
public static void main(String args[])
{
FileReader fr = new FileReader(new File("<put your file path here>"));
while(true)
{
int n=fr.read();
if(n>-1)
{
char ch=(char)fr.read();
System.out.print(ch);
}
}
}
}

Categories