I am trying to simply read in a line from a text file using BufferedReader. Here is the sample code:
try {
BufferedReader reader = new BufferedReader( new FileReader( "data.txt") );
while(reader.readLine() != null )
{
System.out.println(reader.readLine())
}
}
} catch (Exception e) {
e.printStackTrace();
}
The code above seems to not only print out null, but sets the data.txt file to null (as in, the file data.txt would initially have 40kb, and a call to readLine() sets it to 0kb)?
I have no idea why this is occurring, it can locate the file, but sets the file to null?
Can anyone identify why this is occurring?
Thanks.
EDIT !!
The BufferedWriter code is below:
try{
BufferedWriter writer = new BufferedWriter(new FileWriter("data.txt"))
for(int x=0; x<64; x++)
{
writer.write(String.valueOf(data[x]));
}
writer.newLine();
writer.newLine();
}
catch(IOException io)
{};
Not sure why your file contents gets erased however you need to change your while loop to this since you're skipping lines if you use your code.
String line = null;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
Your first readline() is used as while loop condition. Then you write the second readline() to System.out. So you're writing every 2nd line. What you need is this.
String str = null;
while((str=reader.readLine()) != null) {
System.out.println(str);
}
You are printing every second line only, and may also print the end of file null terminator. This is because the while conditional reads the line from your file as well, and that you simply discard this line after checking against null.
Retain the line value in the variable:
String s;
while( (s = reader.readLine()) != null )
{
System.out.println(s);
}
Here's a working sample, similar to your original. Note that closing resources is very important:
import java.io.*;
import java.util.*;
public class ReadFile
{
public static final void main(String[] argv)
{
String fileName="data-2.txt";
writeFile(fileName);
readFile(fileName);
}
private static void writeFile(String fileName)
{
BufferedWriter writer = null;
try
{
writer = new BufferedWriter(new FileWriter(fileName));
for(int x=0; x<64; x++)
{
writer.write("some data\n");
}
writer.newLine();
writer.newLine();
}
catch(IOException x)
{
x.printStackTrace();
}
finally
{
safeClose(writer);
}
}
private static void readFile(String fileName)
{
BufferedReader reader = null;
String line = null;
try
{
reader = new BufferedReader( new FileReader( fileName ));
while((line = reader.readLine()) != null)
{
System.out.println(line);
}
}
catch(IOException x)
{
x.printStackTrace();
}
finally
{
safeClose(reader);
}
}
private static void safeClose(Closeable closeable)
{
if(null != closeable)
{
try
{
closeable.close();
}
catch(IOException x)
{
//ignore -x.printStackTrace()
}
}
}
}
you are reading one line in while loop and then again reading next line in println statement. that means you are when you check the condition that time reader.readLine() does not equal to null, but when you read in println then it become null .`
while(reader.readLine() != null )
{
System.out.println(reader.readLine())
}
you should write your code in this way:
String line = null;
while((line=reader.readLine()) != null)
{
System.out.println(line) ;
}
did you close your writer object? you should close your writer object inside finally block this way.
this might help you to resolve your problem.
finally
{
if(null != writer)
{
try
{
writer.close();
}
catch(IOException ioException)
{
}
}
}
Related
I have a rather tricky question
Is there a way to check if something has been written into a file?
This is a piece of code written by Eric Petroelje, and I need to check if the "Hello world" has been written into a file.
This would be useful for checking if a big number is written to a text file.
Thank you in advance!
public class Program {
public static void main(String[] args) {
String text = "Hello world";
BufferedWriter output = null;
try {
File file = new File("example.txt");
output = new BufferedWriter(new FileWriter(file));
output.write(text);
} catch ( IOException e ) {
e.printStackTrace();
} finally {
if ( output != null ) {
output.close();
}
}
}
}
Read the file after having written it
public boolean writeToTXT(String text, String path)
{
BufferedWriter output = null;
try {
File file = new File(path);
output = new BufferedWriter(new FileWriter(file));
output.write(text);
output.flush();
} catch ( IOException e ) {
e.printStackTrace();
} finally {
if ( output != null ) {
output.close();
}
}
try(BufferedReader br = new BufferedReader(new FileReader(path))) {
StringBuilder sb = new StringBuilder();
String line = br.readLine();
while (line != null) {
sb.append(line);
sb.append(System.lineSeparator());
line = br.readLine();
}
return sb.toString().equals(text); }
}
I am unable to compile the program. The problem is in the last line "out.close". Please tell me how to rectify it and why it is causing a problem.
import java.io.*;
public class Test {
public static void main(String args[]) throws IOException {
try {
BufferedReader in = new BufferedReader(new FileReader(args[0]));
BufferedWriter out = new BufferedWriter(new FileWriter(args[1]));
String line;
line = in.readLine();
while (line != null) {
out.write(line, 0, line.length());
out.newLine();
line = in.readLine();
}
} finally {
out.close();
}
}
}
You have to declare BufferedWriter out variable outside of try-finally block, because the variables declared in try block are out of scope in finally, it's called block scope. The code should be like:
BufferedWriter out = null;
try {
BufferedReader in = new BufferedReader(new FileReader(args[0]));
out = new BufferedWriter(new FileWriter(args[1]));
String line;
line = in.readLine();
while (line != null) {
out.write(line, 0, line.length());
out.newLine();
line = in.readLine();
}
} finally {
if (out != null)
out.close();
}
Or as it's said in comments, if Java version is 7 or above, you should use try-with-resources:
try(BufferedReader in = new BufferedReader(new FileReader(args[0]));
BufferedWriter out = new BufferedWriter(new FileWriter(args[1])))
{
String line;
line = in.readLine();
while (line != null) {
out.write(line, 0, line.length());
out.newLine();
line = in.readLine();
}
}
In that case, you don't need to close it manually in finally block.
Try with Resources (Java 7+). In this case, no need for close statements. Resources declared inside try will be auto closed.
try(BufferedReader in = new BufferedReader(new FileReader(args[0]));
BufferedWriter out = new BufferedWriter(new FileWriter(args[1])))
{
String line;
line = in.readLine();
while (line != null) {
out.write(line, 0, line.length());
out.newLine();
line = in.readLine();
}
} catch (FileNotFoundException e) {
} catch (IOException e) {
} finally {
}
You need to declare your out variable outside of yur try . . . finally block. Since try and finally are two different scopes, out is not defined in your finally block.
I have written the Java code to read from one file and write to a new file. The file from which I am reading has 5000 lines of records, but when I am writing to a new file I am able to write only between 4700-4900 records.
I think may be I am simultaneously reading from a file and writing to a file, which might be creating a problem.
My code is as follows:
Reading from a file:
public String readFile(){
String fileName = "/home/anand/Desktop/index.txt";
FileReader file = null;
try {
file = new FileReader(fileName);
BufferedReader reader = new BufferedReader(file);
String line = "";
while ((line = reader.readLine()) != null) {
line.replaceAll("ids", "");
System.out.println(line);
returnValue += line + "\n";
}
return returnValue;
} catch (Exception e) {
throw new RuntimeException(e);
} finally {
if (file != null) {
try {
file.close();
} catch (IOException e) {
// Ignore issues during closing
}
}
}
}
Writing to a file:
public void writeFile(String returnValue){
String newreturnValue = returnValue.replaceAll("[^0-9,]", "");
String delimiter = ",";
String newtext ="";
String[] temp;
temp = newreturnValue.split(delimiter);
FileWriter output = null;
try {
output = new FileWriter("/home/anand/Desktop/newinput.txt");
BufferedWriter writer = new BufferedWriter(output);
for(int i =0; i < temp.length ; i++){
writer.write("["+i+"] "+temp[i]);
writer.newLine();
}
} catch (Exception e) {
throw new RuntimeException(e);
} finally {
if (output != null) {
try {
output.close();
} catch (IOException e) {
// Ignore issues during closing
}
}
}
}
I need the suggestion to how to simultaneously read and write to a file.
You need to close writer instead of output. The BufferedWriter may not be writing all of the lines, and won't since you never close it.
You have to close the writer object. The last couple lines probably haven't been flushed onto the text file.
In addition, are you aware of the try-with-resource introduced in Java 7? You can condense your code to this by utilizing it:
public String readFile(){
String fileName = "/home/anand/Desktop/index.txt";
try(BufferedReader reader = new BufferedReader(new FileReader(filename)) {
String line = "";
while ((line = reader.readLine()) != null) {
line.replaceAll("ids", "");
System.out.println(line);
returnValue += line + "\n";
}
return returnValue;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
By doing this, Java will automatically close the reader object for you once the try block completes, regardless of whether or not an exception was thrown. This makes it easier to read your code :)
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);
}
}
}
}
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();
}
}
}