So, I'm trying to make a program that can write and then read the exact same text file using only FileWriter and FileReader, but for some reason, when I put both of these classes at the same code, FileWriter works properly, but FileReader does not, and I get an empty output.
import java.io.*;
import java.util.Scanner;
public class ex2 {
public static void main(String[] args) {
File file = new File("C:\\a.txt");
Scanner scanner = new Scanner(System.in);
try {
FileReader reader = new FileReader(file);
FileWriter writer = new FileWriter(file);
writer.write(scanner.nextLine());
int ch;
while ((ch = reader.read()) != -1) {
System.out.println((char)ch);
}
scanner.close();
reader.close();
writer.close();
} catch (Exception e) {
}
}
}
That's the code I'm talking about. I can write anything to a.txt, but reader does not seem to be able to read a thing. The weird part is, if I use the exact same code but without the file writing parts, FileReader works normally as it should. What am I doing wrong? Thanks in advance!
FileWriter objects are buffered. That means they won't write everything you give them as soon as you call write. They'll wait until they have a certain amount to write and then write it all at once. Just add this line:
writer.flush();
between your writing and your reading.
Related
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
public class FileHandling1 {
public static void main(String[] args){
try{
File file = new File("FileHandlingExample1.txt", "US-ASCII");
FileWriter writer = new FileWriter(file);
writer.write("This is the first line.");
writer.write("This is the seccond line.");
writer.write("This is the third line.");
writer.flush();
writer.close();
}catch(IOException exception){
System.out.print("This is an IO Exception");
}
}
}
Output :- This is an IO Exception.
I am new to File Handling in Java. There are no errors in the program. It gives an IO Exception. Why is that?
I don't know exactly the path where it is located your file but this is probably wrong :
File file = new File("FileHandlingExample1.txt", "US-ASCII");
It means your file US-ASCII has as parent folder : FileHandlingExample1.txt.
This is the File constructor that you are using :
public File(String parent, String child)
You probably reversed the order of arguments.
And this statement :
FileWriter writer = new FileWriter(file);
throws an IOException if the named file exists but is a directory rather than a regular file, does not exist but cannot be created, or cannot be opened for any other reason.
This code smells because you dont expose what actually going wrong, you hide information about exception and simple print "bad things happen" you need to print stack trace of your exception and you will be see what actually happen.
Perhaps you file doesn't exist yet, you need to create it before doing something with it, also pay attention how dou you create file, you need only path, before use something will be great to read javadocs File class javaodoc
public class FileHandling1 {
public static void main(String[] args){
try{
File file = new File("FileHandlingExample1.txt");
file.createNewFile();
FileWriter writer = new FileWriter(file);
writer.write("This is the first line.");
writer.write("This is the seccond line.");
writer.write("This is the third line.");
writer.flush();
writer.close();
}catch(IOException e){
e.printStackTrace();
}
}
}
This question already has an answer here:
Java PrintWriter not working
(1 answer)
Closed 6 years ago.
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class FileGenerator {
/**
* #param args
*/
public static void main(String[] args) {
File outputFile;
BufferedReader reader;
FileWriter fileWriter;
try {
outputFile = new File("test.txt");
outputFile.createNewFile();
fileWriter = new FileWriter(outputFile, false);
reader = new BufferedReader(new FileReader("template.txt"));
StringBuilder sb = new StringBuilder();
String line = reader.readLine();
while (line != null) {
sb.append(line);
sb.append(System.lineSeparator());
line = reader.readLine();
}
String everything = sb.toString();
fileWriter.write(everything);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
}
}
}
The fileWriter creates test.txt but the string inside of test.txt is empty. i want it doesnt happen empty. by the way you may say "String everything" can be empty. But it isnt. When i try without reader txt i mean "String everything = "some text", it happens same. it happens empty
The file is empty because the contents of everything are smaller than the operating systems and / or Java's I/O buffers, and the program ends without properly closing the file.
When you write something to a file, and you need to ensure that it is written without closing the file already, call flush().
Whenever you open an I/O resource, close it using close() after use. close() implies flushing the buffers.
Java 7 provides try-with-resources for that, like this:
try (FileWriter writer = new FileWriter("foo.txt")) {
writer.write("Hello, world!\n");
writer.flush();
// do more stuff with writer
} // <- closes writer implicitly as part of the try-with-resources feature
As suggested in the comments, you need to do fileWriter.close() in order to close the output stream. If it is a buffered writer, then closing it not necessary as explained here.
Is it necessary to close a FileWriter, provided it is written through a BufferedWriter?
I wrote a program to write in a file...
package iofile;
import java.io.*;
public class WriteFile {
public static void main(String[] args) {
String s;
File file=new File("C:\\Users\\Rajesh\\oacert\\Learn\\src\\iofile\\raj.txt");
InputStreamReader isr=new InputStreamReader(System.in);
BufferedReader br=new BufferedReader(isr);
try{
PrintWriter pr=new PrintWriter(new BufferedWriter(new FileWriter(file,true)));
System.out.println("enter to write in a file...");
s=br.readLine();
while(s!=null){
pr.println(s);
s=br.readLine();
}
pr.close();
}
catch(Exception e){
}
}
}
But it's unable to write anything in raj.txt. What's causing this? Thanks in Advance
NOTE: raj.txt exists in the mentioned directory...
I don't think s can ever be null in your code. You should better use a terminating string to exit the program. Try replacing this:
while(s!=null){
with
while(!s.equals("exit")){
and enter 'exit' to terminate the loop
Use write method.
Put an end condition, such as s.equalsIgnoreCase("Exit")
Call method flush;
Try the following code.
while(!s.equalsIgnoreCase("Exit")){
pr.write(s);
pr.write("\n");
s=br.readLine();
}
pr.flush();
pr.close();
I have a file, I know that file will always contain only one word.
So what should be the most efficient way to read this file ?
Do i have to create input stream reader for small files also OR Is there any other options available?
Well something's got to convert bytes to characters.
Personally I'd suggest using Guava which will allow you to write something like this:
String text = Files.toString(new File("..."), Charsets.UTF_8);
Obviously Guava contains much more than just this. It wouldn't be worth it for this single method, but it's positive treasure trove of utility classes. Guava and Joda Time are two libraries I couldn't do without :)
Use Scanner
File file = new File("filename");
Scanner sc = new Scanner(file);
System.out.println(sc.next()); //it will give you the first word
if you have int,float...as first word you can use corresponding function like nextInt(),nextFloat()...etc.
Efficient you mean performance-wise or code simplicity (lazy programmer)?
If it is the second, then nothing I know beats:
String fileContent = org.apache.commons.io.FileUtils.readFileToString("/your/file/name.txt")
- Use InputStream and Scanner for reading the file.
Eg:
public class Pass {
public static void main(String[] args){
File f = new File("E:\\karo.txt");
Scanner scan;
try {
scan = new Scanner(f);
while(scan.hasNextLine()){
System.out.println(scan.nextLine());
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
- Guava Library handles this beautifully and efficiently.
Use BufferedReader and FileReader classes. Only two lines of code will suffice to read one word/one line file.
BufferedReader br = new BufferedReader(new FileReader("Demo.txt"));
System.out.println(br.readLine());
Here is a small program to do so. Empty file will cause to print 'null' as output.
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class SmallFileReader
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new FileReader("Demo.txt"));
System.out.println(br.readLine());
}
}
first time post here.
I am in the process of writing a Java program that takes an input text file, reads the contents, and then prints them to the screen and also creates an output file with the contents. I have set up the necessary writers, but when I try to use BufferedReader readername = new BufferedReader(new FileReader(inFile)); it gives me the error in the title.
Any ideas what's causing it?
Here's the code.
public class FileReader
{
public static void main(String[] args) throws IOException
{
try
{
File inFile = new File("inputText.txt");
BufferedReader reader = new BufferedReader(new FileReader(inFile));
String line = null;
BufferedWriter writer = new BufferedWriter(new FileWriter("Contents.txt"));
while ((line=reader.readLine()) != null)
{
writer.write(line);
System.out.println("File 'Contents.txt' successfully written");
System.out.println(line);
}
}
catch (IOException e)
{
System.out.println(e);
}
}
}
Use the fully qualified class name java.io.FileReader since you have a class already called FileReader when calling a BufferedReader, like so:
BufferedReader reader = new BufferedReader(new java.io.FileReader(inFile));
Without fully qualifying your FileReader (or specifying imports), the compiler will use your declared FileReader.
The problem here is that your class name is FileReader and you want to use java.io.FileReader hence compiler is confused and instead of java.io.FileReader it assumes it be your class. Basically your ClassName shadows the name from java.io package.
Rename your class to something else like MyFileReader or use fully qualified named java.io.FileReader