PrintWriter issues - java

I am writing a program, designed to ping an online database, and write a log of the status to a .txt.
Whenever i run the program and open the .txt, the timestamp tells me that it has just been changed, but it is blank.
public static void printToFile(String text) {
String fileName = "log.txt";
PrintWriter outputStream = null;
try {
outputStream = new PrintWriter(fileName);
System.out.println("Printing to txt");
outputStream.println("Debug");
} catch (FileNotFoundException e) {
System.out.println("Error opening the file " + fileName);
outputStream.close();
}
}
public static void pingDatabase(Connection conn) throws SQLException, InterruptedException {
Date timeStamp = new Date(System.currentTimeMillis());
do {
if (conn.isValid(10000)) {
System.out.println("Printtofile called");
printToFile("Database is Online");
} else {
printToFile("Database is Offline");
}
Thread.sleep(10000);
} while (true);
}

You aren't closing, or therefore flushing, your PrintWriter unless there is an exception.
You also need to open your output file in append mode, given your current code, but it would make more sense to keep it open. The overhead of opening and closing a file per message is enormous.

As it is log you might need to append the content instead of writing every time and need to flush the content to log file after writing.
public static void printToFile(String text) {
String fileName = "log.txt";
PrintWriter outputStream=null;
try {
outputStream =new PrintWriter(new FileWriter(fileName,true));
System.out.println("Printing to txt");
outputStream.append(text+"\n");
outputStream.flush();//flushing to file
} catch (IOException e) {
e.printStackTrace();
System.out.println("Error opening the file " + fileName);
}
finally{
outputStream.close();
}
}
new FileWriter(fileName,true) FileWriter is subclass of OutPutStreamWriter and true for opening in append mode

Related

Generating Code into an existing file with Java

I am trying to write a code that will generate code into an already existing HTML File. It seems like I can not reach the existing HTML file in my repository.
I would be happy if someone could help.
Here is the method that should do the code generation:
public static void generate() {
PrintWriter pWriter = null;
try {
pWriter = new PrintWriter(new BufferedWriter(new FileWriter("<filename>.html"))); //and path
pWriter.println("<code we want to put in>");
} catch (IOException ioe) {
ioe.printStackTrace();
} finally {
if (pWriter != null){
pWriter.flush();
pWriter.close();
}
}
}
Check your file read and write access. If you use Mac-OS or linux try to execute chmod 666 .html
If you use Java SE 7+, you can use try-with-resources with PrintWriter.
Check the path to your file.
Try this code below:
public static void generate() {
try (PrintWriter pWriter = new PrintWriter(new File("test.html"))){
pWriter.println("<CODE>");
pWriter.flush();
} catch (IOException ioe) {
ioe.printStackTrace();
}
}

Java: PrintWriter not writing in file

I ran over some problem with PrintWriter. I wrote some code that simply takes some input from a file and outputs it to another one.
Though a file is created, the file remains empty. The wanted input can be easily printed out in the console, which means the FileInputStream is working correctly.
Why is PrintWriter not printing anything?
public static void writeInFile(File in, File out) throws FileNotFoundException {
PrintWriter outputStream = null
Scanner scanner = new Scanner(new FileInputStream(in));
outputStream = new PrintWriter(new FileOutputStream(out));
outputStream.print("test");
while(scanner.hasNext()) {
outputStream.print(scanner.nextLine() + "\n");
}
scanner.close();
}
Make sure you always close your OutputStreams:
while(scanner.hasNext()) {
String s = scanner.nextLine();
outputStream.print(s+"\n");
System.out.println("Test "+s); //d.h. das Problem liegt am outputstream
}
outputStream.close();
scanner.close();
Edit: When you close the outputStream it calls flush automatically, which writes the buffer to the file. Without closing it the buffer may never be emptied/written to the file, as was the case here.
Also see this answer.
When dealing with IO which requires cleanup, I prefer to use auto resource cleanup. This is all you need at the most basic level:
public static void writeInToOut(InputStream in, OutputStream out) {
try(PrintWriter outputStream = new PrintWriter(out);
Scanner scanner = new Scanner(in)) {
while(scanner.hasNext()) {
outputStream.print(scanner.nextLine()+"\n");
}
}
}
You can now overload this function in several ways:
public static void writeInToOut(File file, OutputStream out) {
try (InputStream in = new FileInputStream(file)) {
writeInToOut(in, out);
} catch (IOException e) {
Logger.getAnonymousLogger().log(Level.WARNING, "IOError", e);
}
}
public static void writeInToOut(File inFile, File outFile) {
try (InputStream in = new FileInputStream(inFile);
OutputStream out = new FileOutputStream(outFile)) {
writeInToOut(in, out);
} catch (IOException e) {
Logger.getAnonymousLogger().log(Level.WARNING, "IOError", e);
}
}
public static void writeStdInToFile(File file) {
try (OutputStream out = new FileOutputStream(file)) {
writeInToOut(System.in, out);
} catch (IOException e) {
Logger.getAnonymousLogger().log(Level.WARNING, "IOError", e);
}
}

Writing to file in java - close or flush

I'm writing a logger to my java program (in csv format) with bufferedWriter and FileWriter.
When i open the csv file while the program is running and continues writing to the file, I got this exception: "The process cannot access the file because it is being used by another process".
What i want is when i open the csv file while the program is running, The csv file will open in read mode and the program will writing successfully to the file.
I solved it by changing the closing of bufferedWriter and FileWriter to .flush() instead of .close()
Original minimal logger code (with the original close function)
public class logger {
private BufferedWriter bw = null;
private FileWriter fw = null;
private File file = null;
logger(String nclass) {
path = "c:\\test\\test.csv";
this.file = new File(path);
// Check if the file is already exist.
if (!file.exists()) {
file.createNewFile();
}
fw = new FileWriter(file.getAbsoluteFile(), true);
bw = new BufferedWriter(fw);
}
public void writeToFile(String msg) {
entryWrite();
try {
fw = new FileWriter(file.getAbsoluteFile(), true);
bw = new BufferedWriter(fw);
fw.append(msg);
} catch (IOException e) {
e.printStackTrace();
} finally {
close();
exitWrite();
}
}
}
private void close() {
try {
if (bw != null) {
bw.close();
bw = null;
}
if (fw != null) {
fw.close();
fw = null;
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
My solution function
private void close() {
try {
if (bw != null) {
bw.flush();
bw = null;
}
if (fw != null) {
fw.flush();
fw = null;
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
Now my answer is if it is ok not to close the stream and just use with flush?
Can there be any problems later? Because in all my tests its run well.
Thanks !!
Would it be ok some honesty?, in a very humble way. Sorry but stinky code:
why setting to null "bw" and "fw"?, globals?, why?
"ex.printStackTrace();" ? really?, no log4j or alike?
why not using a finally block?, what happens if an exception occurs while reading writing the file?
Someone has already answered this, for code refer to this excellent answer:
Is it necessary to close a FileWriter, provided it is written through a BufferedWriter?
Just do bufferedWriter object close.
bw.close();
say, you have a large file.txt.
Now u are gonna take something from a file and make a new smaller text file each time.
in that case,
somehow you have to write some lines of code to determine when you finish writing on a particular file. Then use flag to write bw.close();
eventually, you have to initialize the second file and do your task. then bw.close();
if you don't write fw.close(), then the file will be empty.
so, make sure each file writing operation you have to write bw.close()

File not found exception even after bufferedwriter close

New edit:
Now i found the cause, it is because there are two servers and it write into temp folder in 1st server and try to read from the 2nd one. But I still didn't find a solution for this unless write to Amazon S3 and read from there.
I tried to export csv with struts2 action. However if I tried to export 10 times i can only succeed once, all the others failed with File not found exception (if I refresh the link again, the file can be downloaded). Here is my code:
public String exportFile(String fileName) {
File exportFile = null;
try {
if (CollectionUtils.isEmpty(receipts)) {
return "";
}
exportFile = File.createTempFile(fileName, ".csv");
exportFile.deleteOnExit();
try (BufferedWriter fw = new BufferedWriter(new FileWriter(exportFile))) {
try {
fw.write("test");
} finally {
fw.close();
}
}
return exportFile.getPath();
} catch (Exception ex) {
logger.error("Error exporting report. ", ex.getMessage());
}
return "";
}
String getStreamFromPath(String filePath) {
try {
File downloadFile = new File(filePath);
fileInputStream = new FileInputStream(downloadFile);
return SUCCESS;
} catch (IOException e) {
log.error(e.getMessage(), e);
return ERROR;
}
}
This is really weird, when i test in another server it works totally fine. Any ideas?

Clearing File content in Internal Storage on Android

I have a logging class for writing into a file in the app's internal storage space. Whenever the log file exceeds the size limit. For clearing the contents, I am closing the current FileOutputStream and creating a new stream with Write mode and closing it. Is there a way better way for accomplishing this:
public final void clearLog() throws IOException {
synchronized (this) {
FileOutputStream fos = null;
try {
// close the current log file stream
mFileOutputStream.close();
// create a stream in write mode
fos = mContext.openFileOutput(
LOG_FILE_NAME, Context.MODE_PRIVATE);
fos.close();
// create a new log file in append mode
createLogFile();
} catch (IOException ex) {
Log.e(THIS_FILE,
"Failed to clear log file:" + ex.getMessage());
} finally {
if (fos != null) {
fos.close();
}
}
}
}
You could also overwrite your file with nothing.
UPDATE:
There seems to be a better option with getFilesDir () Have a look at this question How to delete internal storage file in android?
Write empty data into file:
String string1 = "";
FileOutputStream fos ;
try {
fos = new FileOutputStream("/sdcard/filename.txt", false);
FileWriter fWriter;
try {
fWriter = new FileWriter(fos.getFD());
fWriter.write(string1);
fWriter.flush();
fWriter.close();
} catch (Exception e) {
e.printStackTrace();
} finally {
fos.getFD().sync();
fos.close();
}
} catch (Exception e) {
e.printStackTrace();
}
In this code:
fos = new FileOutputStream("/sdcard/filename.txt", false);
FALSE - for write new content. If TRUE - text append to existing file.
public void writetofile(String text){ // text is a string to be saved
try {
FileOutputStream fileout=openFileOutput("mytextfile.txt", false); //false will set the append mode to false
OutputStreamWriter outputWriter=new OutputStreamWriter(fileout);
outputWriter.write(text);
outputWriter.close();
readfromfile();
Toast.makeText(getApplicationContext(), "file saved successfully",
Toast.LENGTH_LONG).show();
}catch (Exception e) {
e.printStackTrace();
}
}

Categories

Resources