I was testing out writing to files with this code:
package files;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
public class FileTest1
{
public static void main(String[] args)
{
try
{
try
{
File f = new File("filetest1.txt");
FileWriter fWrite = new FileWriter(f);
BufferedWriter fileWrite = new BufferedWriter(fWrite);
fileWrite.write("This is a test!");
}
catch(FileNotFoundException e)
{
System.out.print("A FileNotFoundException occurred!");
e.printStackTrace();
}
}
catch(IOException e)
{
System.out.println("An IOException occurred!:");
e.printStackTrace();
}
}
}
Nothing happens when it is executed.
"This is a test!" is not written, nor the StackTrace or the "A/An [exception] occurred!"...
I don't know what's causing the problem. I have fileTest1.txt in the package right under the file...
A BufferedWriter does just that, it buffers the output before it is written to the destination. This can make the BufferedWriter faster to use as it doesn't have to write to a slow destination, like a disk or socket, straight away.
The contents will be written when the internal buffer is to full, you flush the Writer or close the writer
Remember, if you open it, you should close it...
For example...
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class TestFileWriter {
public static void main(String[] args) {
try {
BufferedWriter fileWrite = null;
try {
File f = new File("filetest1.txt");
System.out.println("Writing to " + f.getCanonicalPath());
FileWriter fWrite = new FileWriter(f);
fileWrite = new BufferedWriter(fWrite);
fileWrite.write("This is a test!");
fileWrite.flush();
} catch (FileNotFoundException e) {
System.out.print("A FileNotFoundException occurred!");
e.printStackTrace();
} finally {
try {
// Note, BufferedWriter#close will also close
// the parent Writer...
fileWrite.close();
} catch (Exception exp) {
}
}
} catch (IOException e) {
System.out.println("An IOException occurred!:");
e.printStackTrace();
}
try {
BufferedReader br = null;
try {
File f = new File("filetest1.txt");
System.out.println("Reading from " + f.getCanonicalPath());
FileReader fReader = new FileReader(f);
br = new BufferedReader(fReader);
String text = null;
while ((text = br.readLine()) != null) {
System.out.println(text);
}
} catch (FileNotFoundException e) {
System.out.print("A FileNotFoundException occurred!");
e.printStackTrace();
} finally {
try {
// Note, BufferedWriter#close will also close
// the parent Writer...
br.close();
} catch (Exception exp) {
}
}
} catch (IOException e) {
System.out.println("An IOException occurred!:");
e.printStackTrace();
}
}
}
If you are using Java 7, you may like to take a look at try-with-resources
After
fileWrite.write("This is a test!");
you have to flush() the writer. To avoid leaking of resources you should also close() the writer (which automatically flushes it).
So you need to add:
fileWrite.close();
Use BufferedWriter.flush() and BufferedWriter.close(). Additional info here http://docs.oracle.com/javase/7/docs/api/java/io/BufferedWriter.html
You must call close() or at least flush() on the writer in order for the buffer to be really written to the file.
Related
I made the program in java to convert the text in the file in the uppercase but it erases data instead of converting it
But when I take data from 1 file and write converted data into another file, it works fine.
So I got problem that how can I do this using single file.
Here below is my code, Tell me how to correct this?
import java.io.FileReader;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.FileWriter;
public class uppercase{
public static void main(String[] args) {
try {
FileReader reader = new FileReader("e.txt");
FileWriter writer = new FileWriter("e.txt");
int data;
int data2;
while((data=reader.read())!= -1) {
data2=Character.toUpperCase(data);
writer.write(data2);
}
reader.close();
writer.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
this is bad idea, because you are writing to same file you are reading from. You should either:
Load complete file to memory, close it and then dump it to same file.
Save to different file and rename (better)
firstly you open a stream to read from file and append the result to a String variable and at the end of reading, you write all the data to the file:
try {
FileReader reader = new FileReader("e.txt");
String result = "";
int data;
int data2;
while ((data = reader.read()) != -1) {
data2 = Character.toUpperCase(data);
result += (char)data2;
}
reader.close();
System.out.println(result);
FileWriter writer = new FileWriter("e.txt");
writer.write(result);
writer.flush();
writer.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
I am currently trying to program a small API, but with my writeToFile method, even if I use true in the method, it deletes everything that is in the file and only writes in the text of the user (#param text).
What did I do wrong ? I tried to print the string, but it appears to be empty. If I only use the readFile method of mine, it reads out the whole file correctly.
Need help.
package at.tornaduuu.usefullapi.files;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class FileUtils {
public static void writeToFile(String text, File file, boolean keepIndexText) {
try {
String indexText = "";
FileWriter fw = new FileWriter(file);
if (keepIndexText) {
indexText = FileUtils.readFile(file);
System.out.println(indexText);
FileUtils.clearFile(file);
fw.write(indexText + text);
fw.close();
}
else {
fw.write(text);
fw.close();
}
}
catch (IOException e) {
e.printStackTrace();
}
}
public static void clearFile(File file) {
try {
FileWriter fw = new FileWriter(file);
fw.write("");
fw.close();
}
catch (IOException e) {
e.printStackTrace();
}
}
public static String readFile(File file) {
String fileIndex = "";
int unicode;
try {
FileReader fr = new FileReader(file);
try {
while ((unicode = fr.read()) != -1) {
fileIndex += (char) unicode;
}
fr.close();
}
catch (IOException e) {
e.printStackTrace();
}
}
catch (FileNotFoundException e) {
e.printStackTrace();
}
return fileIndex;
}
}
You are not appending to file, you are just rewriting it. That's because FileWriter is not set to append. You can change this:
FileWriter fw = new FileWriter(file); //rewrites file every time write() method is called
to:
FileWriter fw = new FileWriter(file,true); //append text in file when write() is called
and it should work.
You are calling FileWriter(File) which in turn will call FileOutputStream(String name, append = False). So your file is getting truncated before you read content.
There is another constructor FileWriter(File file, boolean append) that you can use with keepIndexText, in such case your FileUtils.clearFile(file); is pretty useless.
Tried to put flush and close everywhere. Still, does not write to file. Changed file location, path of the file, still does not write to the file; however it creates it.
public void filePatient(HashMap<Integer,Patient> collection, String filename) {
// crating a file
File file = new File (filename+".txt");
try (PrintWriter out = new PrintWriter(new FileWriter(file),true)) {
for(Patient i: collection.values()) {
out.write(i.getName());
//out.write(i.getHealthNumber());
}
out.flush();
out.close();
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Your code works as-is.
You can also remove the close, as you use try-with-resources.
Here's a full working example:
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;
public class Main {
public static void main(String[] args) {
Map<String, String> map = new HashMap<>();
map.put("a", "my name");
map.put("b", "your name");
filePatient(map, "c:\\temp\\test");
}
public static void filePatient(Map<String, String> collection, String filename) {
// crating a file
File file = new File(filename + ".txt");
try (PrintWriter out = new PrintWriter(new FileWriter(file), true)) {
for (String name : collection.values()) {
out.write(name);
}
out.flush();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
I want to convert my IO Class from java on Eclipse to the Android API. For some reason it's not working on android!It is giving me a NullPointerException on my Println method. This class is used to create, write, read and open textfiles. My goal is to make all these methods readable on android.
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintStream;
import java.io.PrintWriter;
public class IO {
private static PrintWriter fileOut;
private static BufferedReader fileIn;
public static void createOutputFile(String fileName) {
try {
fileOut = new PrintWriter(new BufferedWriter(new FileWriter(fileName)));
} catch (IOException e) {
System.out.println("*** Cannot create file: " + fileName + " ***");
}
}
public static void openOutputFile(String fileName) {
try {
fileOut = new PrintWriter(new BufferedWriter(new FileWriter(fileName, true)));
} catch (IOException e) {
System.out.println("*** Cannot open file: " + fileName + " ***");
}
}
public static void openOutputFile2(String fileName) {
try {
fileOut = new PrintWriter(new BufferedWriter(new FileWriter(fileName, false)));
} catch (IOException e) {
System.out.println("*** Cannot open file: " + fileName + " ***");
}
}
public static void print(String text) {
fileOut.print(text);
}
public static void println(String text) {
fileOut.println(text);
//System.out.println(text);
}
public static void closeOutputFile() {
fileOut.close();
}
public static void openInputFile(String fileName) {
try {
fileIn = new BufferedReader(new FileReader(fileName));
//System.out.println("opening " + fileName);
} catch (FileNotFoundException e) {
System.out.println("***Cannot open " + fileName + "***");
}
}
public static String readLine()
// throws IOException
// Note: if there's an error in this method it will return IOException
{
try {
return fileIn.readLine();
} catch (IOException e) {
e.printStackTrace();
return "errors";
}
}
public static void closeInputFile() {// throws IOException
// Note: if there's an error in this method it will return IOException
try {
fileIn.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
If you're getting a NullPointerException in println then that would be because 'fileOut' is null.
public static void println(String text) {
fileOut.println(text);
//System.out.println(text);
}
You're actually reacting on your second error because you've ignored the first one. In all cases where you set fileOut you're swallowing (effectively hiding) the error. E.g.
public static void openOutputFile(String fileName) {
try {
fileOut = new PrintWriter(new BufferedWriter(new FileWriter(fileName, true)));
} catch (IOException e) {
//Don't do this, it makes debugging much more difficult.
//Because the root problem is hidden.
//So now you have 2 problems to solve.
//And you've thrown away the information that might have
//helped to solve the problem in the first place.
System.out.println("*** Cannot open file: " + fileName + " ***");
}
}
Stop hiding errors, if something goes wrong you need to find out about it. Because invariably, ignoring errors results in more complex errors later down the line.
Fix you bad exception handling, and you'll be able to track down the root problem (probably file not found or a permission error).
These are the contents of the constructor of a class which is called by the main method.
File f = null;
Scanner s;
try {
f = new File(getClass().getResource("/LOL.txt").toURI());
} catch (URISyntaxException e) {
e.printStackTrace();
}
try {
s = new Scanner(f);
while(s.hasNextLine()) System.out.println(s.nextLine());
} catch (FileNotFoundException e) {
e.printStackTrace();
}
try {
FileWriter fw = new FileWriter(f.getAbsoluteFile(), false);
BufferedWriter bw = new BufferedWriter(fw);
bw.write("LOL");
bw.close();
} catch (IOException e) {
e.printStackTrace();
}
Output in the console:
LOL
The contents of the file remain unchanged even after repeated runs. My IDE is eclipse
You parametrize your FileWriter with boolean append set as false.
Therefore, the same file will be written over every time that given constructor is executed, and "LOL" will be printed in it.
Before printing "LOL", a Scanner reads each line and prints it, hence the LOL printed in our system out.
Also note, you probably want to declare your FileWriter and BufferedWriter out of the try block, so you can flush and close them in a finally block.
This post only contains the initial question, as-is with everything corrected to avoid several resource-related bugs. It assumes Java 6 or lower.
I shouldn't get any upvote so please don't ;)
package so39452286;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.Writer;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
new Main().run();
}
public void run() {
try {
File file = new File(getClass().getResource("/LOL.txt").toURI());
Scanner scanner = null;
try {
scanner = new Scanner(file);
while (scanner.hasNextLine()) {
System.out.println(scanner.nextLine());
}
} finally {
if (scanner != null) {
scanner.close();
}
}
Writer writer = null; // Holds the main resource, not the wrapping ones.
try {
writer = new FileWriter(file.getAbsolutePath(), false);
BufferedWriter bw = new BufferedWriter(writer);
bw.write("LOL");
bw.flush(); // You forgot to flush. Ok, close() does it, but it's always better to be explicit about it.
} finally {
if (writer != null) {
writer.close();
}
}
} catch (Exception e) {
// Do something with e.
e.printStackTrace(System.err);
}
}
}