Repeatedly Writing to a File - java

I'm a moderately-experienced C++ guy slowly learning Java. I'm writing a program which needs to do the following:
Create a simple text file, default directory is fine
As the program runs, periodically write one line of data to the file. Depending on a number of factors, the program may write to the file once or a million times. There is no way of knowing which write will be the last.
I've been researching different ways to do this, and this is the working code I've come up with. There are two files, "PeteProgram.java" and "PeteFileMgr.java" :
/*
"PeteProgram.java"
*/
import java.io.*;
import java.lang.String;
public class PeteProgram {
public static void main(String[] args) throws IOException {
String PeteFilename="MyRecordsFile.txt";
Writer writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(PeteFilename), "utf-8"));
PeteFileMgr MyPeteFileMgr = new PeteFileMgr(writer);
MyPeteFileMgr.AddThisString(writer, "Add this line #1\n");
MyPeteFileMgr.AddThisString(writer, "Add this line #2\n");
MyPeteFileMgr.AddThisString(writer, "Add this line #3\n");
}
}
//=====================================================================================================
//=====================================================================================================
/*
"PeteFileMgr.java"
*/
import java.io.*;
public class PeteFileMgr {
public PeteFileMgr(Writer writer) {
try {
writer.write("File created!");
} catch (IOException ex) {
// report
} finally {
try {writer.close();} catch (Exception ex) {}
}
}
void AddThisString(Writer writer, String AddThis) {
try {
writer.append(AddThis);
} catch (IOException ex) {
// report
} finally {
try {writer.close();} catch (Exception ex) {}
}
}
}
The initial creation of the file works just fine. However, the to-be-added lines are not written into the file. Because the program compiles and runs with no errors, I assume the program tries to write the added lines, fails, and throws an exception. (Unfortunately, I am working with a primitive compiler/debugger and can't see if this is the case.)
Does anyone spot my mistake?
Many thanks!
-P

That's because you're not flushing the Writer. You should call flush from time to time. Also, you should close your Writer at the end of your app, not after writing content into it. close method automatically flushes the contents of the writer.
So, this is how your code should look like:
public class PeteProgram {
public static void main(String[] args) {
String peteFilename = "MyRecordsFile.txt";
//here's when the physical file is created
Writer writer = null;
try {
writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(peteFilename), "utf-8"));
PeteFileMgr peteFileMgr = new PeteFileMgr(writer);
peteFileMgr.addThisString(writer, "Add this line #1\n");
peteFileMgr.addThisString(writer, "Add this line #2\n");
peteFileMgr.addThisString(writer, "Add this line #3\n");
} catch (IOException e) {
//handle the exception
//basic handling
e.printStacktrace();
} finally {
//this is a must!
try { writer.close(); } catch(IOException silent) { }
}
}
}
public class PeteFileMgr {
public PeteFileMgr(Writer writer) {
try {
//this method is not creating the physical file
writer.write("File created!");
} catch (IOException ex) {
// report
} finally {
//remove this call to close
//try {writer.close();} catch (Exception ex) {}
}
}
public void addThisString(Writer writer, String addThis) {
try {
writer.append(addThis);
} catch (IOException ex) {
// report
} finally {
//remove this call to close
//try {writer.close();} catch (Exception ex) {}
}
}
}
Or if using Java 7 or superior using the try-with-resources:
public class PeteProgram {
public static void main(String[] args) {
String peteFilename = "MyRecordsFile.txt";
//here's when the physical file is created
try (Writer writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(peteFilename), "utf-8"))) {
PeteFileMgr peteFileMgr = new PeteFileMgr(writer);
peteFileMgr.addThisString(writer, "Add this line #1\n");
peteFileMgr.addThisString(writer, "Add this line #2\n");
peteFileMgr.addThisString(writer, "Add this line #3\n");
} catch (IOException e) {
//handle the exception
//basic handling
e.printStacktrace();
}
}
}

Related

PrintWriter object variable cannot resolve to type when used in try with resources

I'm trying to create a new PrintWriter object within a try with resources block as below, but it's giving me an error saying outFile cannot be resolved to a type:
public class DataSummary {
PrintWriter outFile;
public DataSummary(String filePath) {
// Create new file to print report
try (outFile = new PrintWriter(filePath)) {
} catch (FileNotFoundException e) {
System.out.println("File not found");
e.printStackTrace();
}
}
EDIT:
A reason why I didn't want to declare the PrintWriter object within the try block is because I want to be able to reference the outFile object in other methods of my class.
It seems like I can't do it with try with resources, so I created it within a normal try/catch/finally block.
The text file is being created. However, when I try to write to file in another method, nothing seems to be printing in the text file, test.txt.
Why is this??
public class TestWrite {
PrintWriter outFile;
public TestWrite(String filePath) {
// Create new file to print report
try {
outFile = new PrintWriter(filePath);
} catch (FileNotFoundException e) {
System.out.println("File not found");
e.printStackTrace();
} finally {
outFile.close();
}
}
public void generateReport() {
outFile.print("Hello world");
outFile.close();
}
}
Instead of trying to do everything in a constructor, I will demonstrate the preferred way to use a try-with-resources and invoke another method. Namely, pass the closeable resource to the other method. But I strongly recommend you make the opener of such resources responsible for closing them. Like,
public void writeToFile(String filePath) {
try (PrintWriter outFile = new PrintWriter(filePath)) {
generateReport(outFile);
} catch (FileNotFoundException e) {
System.out.println("File not found");
e.printStackTrace();
}
}
private void generateReport(PrintWriter outFile) {
outFile.print("Hello world");
}

Java, Exception when trying to deserialize object, problems catching

I have a program that needs to load data at launch. The data comes from a serialized object. I have a method loadData(), which is called upon construction of the Data class. Sometimes, (I.e. after a loss of saveData, or on first program launch on a new system), the file can be empty. (The file will exist though, the method ensures that).
When I try to run the program, I recieve an EOFException. So, in the method, I try to catch it, and just print a line to the console explaining what happened and return to the caller of the method. (so, upon return, the program will think loadData() is complete and has returned. However, it still crashes throwing the exception without printing a line to the console or anything. It is like it is totally ignoring the catch I have in place.
CODE:
protected void loadData()
{
// Gets/creates file object.
saveFileObject = new File("savedata.ser");
if(!saveFileObject.exists())
{
try
{
saveFileObject.createNewFile();
}
catch(IOException e)
{
System.out.println("Uh oh...");
e.printStackTrace();
}
}
// Create file input stream
try
{
fileIn = new FileInputStream(saveFileObject);
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
// Create object input stream
try
{
inputStream = new ObjectInputStream(fileIn);
}
catch(IOException e)
{
e.printStackTrace();
}
// Try to deserialize
try
{
parts = (ArrayList<Part>)inputStream.readObject();
}
catch(EOFException e)
{
System.out.println("EOFException thrown! Attempting to recover!");
return;
}
catch(ClassNotFoundException e)
{
e.printStackTrace();
}
catch(IOException e)
{
e.printStackTrace();
}
// close input stream
try
{
inputStream.close();
}
catch(IOException e)
{
e.printStackTrace();
}
}
Any help please?
Try writing your code like :
protected void loadData() {
// Gets/creates file object.
saveFileObject = new File("savedata.ser");
try {
if (!saveFileObject.exists()) {
saveFileObject.createNewFile();
}
// Create file input stream
fileIn = new FileInputStream(saveFileObject);
// Create object input stream
inputStream = new ObjectInputStream(fileIn);
// Try to deserialize
parts = (ArrayList<Part>) inputStream.readObject();
// close input stream
inputStream.close();
} catch (EOFException e) {
System.out.println("EOFException thrown! Attempting to recover!");
} catch (IOException e) {
System.out.println("Uh oh...");
e.printStackTrace();
}
}
Also note that EOFException is a sub-class of IOException
How about making one try and then making catches respectively like here?

Output text to a file with a class method java

I have a valet class method that should write an hourly wage to a file:
public void hourlyOverall() throws FileNotFoundException
{
PrintWriter out = new PrintWriter("wage info");
new FileOutputStream("wage info", true);
hourlyOverall = tips / hours + hourlyWage;
out.println(hourlyOverall);
}
However, when I run valet.hourlyOverall() in my main method, the file "wage info" is created but nothing is written to it. What am I doing wrong?
First of all use try-catch for Exception handling and then in the finally block close the OutputStream
out.flush();
Somthing like this
try {
PrintWriter out = new PrintWriter("wage info");
hourlyOverall=tips/hours+hourlyWage;
out.println(hourlyOverall);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
finally {
out.flush();
}
I think this is another way to solve your problem, but using another classes
public class valet {
public static void main(String []args)throws IOException
{
try
{
hourlyOverall()
}
catch(IOException ex)
{
System.out.println(ex+"\n");
}
}
public void hourlyOverall() throws IOException
{
FileWriter out = new FileWriter("wage info");
hourlyOverall=tips/hours+hourlyWage;
out.write(hourlyOverall+"\r\n");
out.close();
}
}
You probably shouldn't declare an anonymous FileOutputStream and you should probably close your PrintWriter,
PrintWriter out=new PrintWriter("wage info");
// new FileOutputStream("wage info",true);
hourlyOverall=tips/hours+hourlyWage;
out.println(hourlyOverall);
out.close(); // <-- like that
Do something like this (if java7 or above) :
public void hourlyOverall()
{
try (PrintWriter out=new PrintWriter("wage info")){
//new FileOutputStream("wage info",true);
hourlyOverall=tips/hours+hourlyWage;
out.println(hourlyOverall);
}catch (FileNotFoundException e) {
e.printStackTrace();
}
}
http://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html

java PrintWriter cannot be resolved

I have no idea why I get the message "cannot be resolved" on out in eclipse on the 11th line
import java.io.*;
public class driver {
public static void main(String[] args) {
try {
PrintWriter out = new PrintWriter("output.txt");
}
catch (FileNotFoundException e) {
System.out.print("file not found");
e.printStackTrace();
}
out.print("hello");
out.close();
}
}
OK so now I have this
import java.io.*;
public class driver {
public static void main(String[] args) {
PrintWriter out = null;
try {
out = new PrintWriter("output.txt");
}
catch (FileNotFoundException e) {
System.out.print("file not found");
e.printStackTrace();
}
out.print("hello");
out.close();
}
}
Why doesn't eclipse create a file once I close out?
Declare your PrintWriter before the try block so it's scope isn't limited to the try block.
You can also use new try-with-resource block introduced in JDK 1.7, in this advantage is you don't need to worry about closing any resource which implements Closable Interface.
Then code will look like this:
try (PrintWriter out = new PrintWriter("output.txt"))
{
out.print("hello");
}
catch (FileNotFoundException e)
{
System.out.print("file not found");
e.printStackTrace();
}

FileOuputStream Write bytes for loop, but no data write?

Listing my program fragment as below
public class InStream {
static FileOutputStream file=null;
static {
try {
file = new FileOutputStream("deo.txt");
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
try {
//when i try to replace below infinite loop,
//it is also not able to output my String
//while(ture)
or
//for(;;)
for(int i=0;i<100000;i++){
file.write("AB ".getBytes());
}
//file.flush();
file.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
Run this program -> open deo.txt -> there are no data within this file
but when i comment the for loop just only test below fragment code:
try {
file.write("AB ".getBytes());
file.close();
} catch (Exception e) {
e.printStackTrace();
}
Now i can see the "AB " string in the file. so strange....
Can any one do me a favor?
There is no error in your code. File "deo.txt" must be generate which contains AB AB...............
I tested your code. And it works. But for the deo.txt. You can check its size if it is about 293k. It displays nothing if you open it with Eclipse text editor. But you can view it with other system editor, such as notepad++.

Categories