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);
}
}
}
}
Related
The code is like this:
public class TxtToCsvConverter{
private static final String DATA_FILE_NAME = "/Desktop/ml-1m/movies.dat";
public static void main(String[] args) {
StringBuilder bulider = new StringBuilder();
try{
// Open the file
FileInputStream fileInputStream = new FileInputStream(DATA_FILE_NAME);
// Create a new csv file to store your data
PrintWriter writer = new PrintWriter(new File("result.csv"));
DataInputStream dataInputStream = new DataInputStream(fileInputStream);
BufferedReader reader = new BufferedReader(new InputStreamReader(dataInputStream));
String strLine;
// Read file line by line
while ((strLine = reader.readLine()) != null) {
String[] stringArray = strLine.split("::");
for (int i = 0; i < stringArray.length; i++) {
bulider.append(stringArray[i]);
bulider.append(",");
}
bulider.append("\n");
}
// Close the input stream
dataInputStream.close();
// Write builder into file
writer.write(bulider.toString());
// Save the file
writer.close();
}catch (Exception e) {
// Catch exception if any
System.err.println("Error: " + e.getMessage());
}
}
}
And it appears to come out a error says
Could not find or load main class TxtToCsvConverter.data_preprocess"
I couldn't find the reason. Please help
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;
}
How do you read a file object in java?
File file= new File(filePathName);
if (file.exists()){
filesArrayList.add(file);
}
Depending on the number of processors threads are sent:
a file and a starting (lower bound) and end (upper bound) to read.
File inputFile= (File)filesArrList.get(i);
BufferedInputStream bis= new BufferedInputStream(new FileInputStream (inputFile));
while ((line=bis.readLine())!=null) {
System.out.println(line);
}
Is it possible to read the files in the arraylist?
1 : You can read files stored in ArrayList through the following way.
2 : Yes it is also possible to read files stored in array list.
public class ReadingFiles {
BufferedReader br;
ArrayList<File> list = new ArrayList<>();
ReadingFiles() {
list.add(new File((getClass().getResource("file1.txt")).getPath()));
readFile(list.get(0));
list.add(new File((getClass().getResource("file2.txt")).getPath()));
readFile(list.get(1));
}
public void readFile(File file) {
try {
br = new BufferedReader(new FileReader(file));
String line = br.readLine();
while (line != null) {
System.out.println(line);
line = br.readLine();
}
br.close();
} catch (Exception ex) {
System.out.println("Sorry");
}
}
public static void main(String[] args){
new ReadingFiles();
}
}
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.
Concerning my previous question , I found out that maven can't really output jboss console. So I thought I'd like to make workaround it. Here is the deal:
While jboss is running, it writes console logs into server.log file, so I'm trying to retrieve the data as it comes in, because every few seconds the file is changes/updated by jboss I've encountered some difficulties so I need help.
What I actually need is:
read file server.log
when server.log is changed with adding few more lines output the change
Here is the code so far I got, there is a problem with it, it runs indefinitely and it starts every time from the beginning of the file, I'd like it to continue printing just the new lines from server.log. Hope it makes some sense here is the code:
import java.io.*;
class FileRead
{
public static void main(String args[])
{
try{
for(;;){ //run indefinitely
// Open the file
FileInputStream fstream = new FileInputStream("C:\\jboss-5.1.0.GA\\server\\default\\log\\server.log");
BufferedReader br = new BufferedReader(new InputStreamReader(fstream));
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());
}
}
}
According to the Montecristo suggestion I did this :
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(
"C:\\jboss-5.1.0.GA\\server\\default\\log\\server.log");
BufferedReader br = new BufferedReader(new InputStreamReader(fstream));
String line;
// Read File Line By Line
while ((line = br.readLine()) != null) {
// Print the content on the console
line = br.readLine();
if (line == null) {
Thread.sleep(1000);
} else {
System.out.println(line);
}
}
// Close the input stream
in.close();
} catch (Exception e) {// Catch exception if any
System.err.println("Error: " + e.getMessage());
}
}
}
And it still not working, it just printed the original file.. although the file changes constantly nothing happens.. nothing gets printed out except the original log file.
HERE IS THE SOLUTION: tnx Montecristo
import java.io.*;
class FileRead {
public static void main(String args[]) {
try {
FileInputStream fstream = new FileInputStream(
"C:\\jboss-5.1.0.GA\\server\\default\\log\\server.log");
BufferedReader br = new BufferedReader(new InputStreamReader(fstream));
String line;
while (true) {
line = br.readLine();
if (line == null) {
Thread.sleep(500);
} else {
System.out.println(line);
}
}
} catch (Exception e) {
System.err.println("Error: " + e.getMessage());
}
}
}
Also see :
http://vanillajava.blogspot.co.uk/2012/08/java-memes-which-refuse-to-die.html
I don't know if you're going in the right direction but if I've understood correctly you'll find this useful: java-io-implementation-of-unix-linux-tail-f
You can use RandomAccessFile.
import java.io.IOException;
import java.io.RandomAccessFile;
public class LogFileReader {
public static void main( String[] args ) {
String fileName = "abc.txt";
try {
RandomAccessFile bufferedReader = new RandomAccessFile( fileName, "r"
);
long filePointer;
while ( true ) {
final String string = bufferedReader.readLine();
if ( string != null )
System.out.println( string );
else {
filePointer = bufferedReader.getFilePointer();
bufferedReader.close();
Thread.sleep( 2500 );
bufferedReader = new RandomAccessFile( fileName, "r" );
bufferedReader.seek( filePointer );
}
}
} catch ( IOException | InterruptedException e ) {
e.printStackTrace();
}
}
}