I have a java application that needs to write a lot of data into individual lines in a text file. I wrote the code below to do this, but for some reason, it is not writing anything to the text file. It does create the text file, but the text file remains empty after the program is done running. Can anyone show me how to fix the code below so that it actually fills the output file with as many lines of output as it is called upon to do?
public class MyMainClass{
PrintWriter output;
MyMainClass(){
try {output = new PrintWriter("somefile.txt");}
catch (FileNotFoundException e1) {e1.printStackTrace();}
anotherMethod();
}
void anotherMethod(){
output.println("print some variables");
MyOtherClass other = new MyOtherClass();
other.someMethod(this);
}
}
public class MyOtherClass(){
void someMethod(MyMainClass mmc){
mmc.output.println("print some other variables")
}
}
How you are going about doing this seems very strange to me. Why don't you write one method that takes in a string and then writes it to your file? Something like this should work fine
public static void writeToLog(String inString)
{
File f = new File("yourFile.txt");
boolean existsFlag = f.exists();
if(!existsFlag)
{
try {
f.createNewFile();
} catch (IOException e) {
System.out.println("could not create new log file");
e.printStackTrace();
}
}
FileWriter fstream;
try {
fstream = new FileWriter(f, true);
BufferedWriter out = new BufferedWriter(fstream);
out.write(inString+"\n");
out.newLine();
out.close();
} catch (IOException e) {
System.out.println("could not write to the file");
e.printStackTrace();
}
return;
}
Use the other constructor:
output = new PrintWriter(new FileWriter("somefile.txt"), true);
According to JavaDoc:
public PrintWriter(Writer out, boolean autoFlush)
Creates a new PrintWriter.
Parameters:
out - A character-output stream
autoFlush - A boolean; if true, the println, printf, or format methods will flush the output buffer
Use other constructor new PrintWriter(new PrintWriter("fileName"), true) for auto-flushing data or
Use flush() and close() when you're done writing
Related
I have a Java program littered with values I want to log to a txt file. I'm new to the language and finding it not so straight forward.
I created a Logger class:
public static void loggerMain(String content) {
try {
PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("debug.txt", true)));
out.println(content);
out.close();
} catch (IOException e) {
//exception handling left as an exercise for the reader
}
}
I then call the method in another class:
Logger.loggerMain("testing");
It logs the String but if I then run the script again, it will append the same String to a new line.But I don't want the same println to be appended each time the script is called. I want to override the file. How would I go about this?
If I change the FileWriter argument to False, the file will only log the latest call to the method. e.g.:
Logger.loggerMain("testing1");
Logger.loggerMain("testing2");
Only Logger.loggerMain("testing2"); will be logged. I know why, it's because I'm creating a new file each time I call the method.. but I really don't know the solution to this!
If I understood you correctly you want to clear the log for every time the programm is executed. You can do this with the following addition to the Logger class:
class Logger {
private static boolean FIRST_CALL = true;
public static void loggerMain(String content) {
try {
PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("debug.txt", !FIRST_CALL)));
if(FIRST_CALL){
FIRST_CALL = false;
}
out.println(content);
out.close();
} catch (IOException e) {
//exception handling left as an exercise for the reader
}
}
}
With the variable FIRST_CALL we track if the logger has been executed for the first time in the current script context. If it is, we overwrite the file, by passing in false (!FIRST_CALL) into the FileWriter
Just a re-iteration of the other answer:
class Logger {
private static boolean FIRST_CALL = true;
public static void loggerMain(String content) {
try (
PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("debug.txt", !FIRST_CALL)))) {
FIRST_CALL = false;
out.println(content);
} catch (IOException e) {
//exception handling left as an exercise for the reader
}
}
}
try-with-resources will spare you an explicit close() call, and will properly close the resource regardless of completing the block normally or with an exception.
This one is subjective: as the code will touch FIRST_CALL anyway, I feel it simpler to set it without the extra check.
This is a question about: Receiving message and saving it into a file in current directory.
My issue is that, even though the messages are received, i am unable to write them into a file. The file is updated but it is empty. Yet the messages are printed on the interface. What i want is the message to be inside the file, not printed on the interface.
This is the code
public void receiveMessages() {
File file = new File ("msgs.txt");
if (!file.exists()) {
try {
file.createNewFile();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
PrintWriter printWriter = null;
try {
printWriter = new PrintWriter(file);
SealedObject encrypedSealedObject = null;
while(true){
try {
String message = this.crypto.decryptMsg(encrypedSealedObject);
printWriter.println(message);
}
catch (IOException e) {
break;
}
}
}
//catching exceptions ``here.... etc
}
Thank you for your help!
PrintWriter implements Flushable interface.
A Flushable is a destination of data that can be flushed. The flush
method is invoked to write any buffered output to the underlying
stream.
So, you have to flush your output to the file. So, you have to use pw.flush().
And above code will rewrite the file and not append the successive messages. If this is your requirement then its ok. But, I would suggest the following:
PrintWriter pw = null;
if (appendToFile) {
pw = new PrintWriter(new FileWriter(filename, true));
} else {
pw = new PrintWriter(new FileWriter(filename));
}
No need of using 2 try and catch as in both statement you are throwing IOException. And I would suggest to throw Throwable and handle the error in top layer it's good practice and easier maintenance. A function call must only perform logic.
Hello this is my code eclipse is telling me the hire ArrayList needs to be an int and I want to print the toString() method in hire class so I can print everything in the array
public static void save() {
try {
File file = new File("D:/Assignment/filename.txt");
// If file does not exists then create it
if (!file.exists()) {
file.createNewFile();
}
FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
for(Hire hire:HireList)
bw.write(hire);
bw.close();
System.out.println("Done");
} catch (IOException e) {
e.printStackTrace();
}
}
If you want to write the hire.toString(), simply use this :
bw.write(hire.toStrig());
else Javac can't know if your calling bw.write(int)or bw.write(String) or other ...
I need to list all subfolders in a directory and written on to text file.But when i coded only the last subfolder is only written on to the file.Please help.I am a beginner to Java.
public class Main {
// private Object bufferedWriter;
/**
* Prints some data to a file using a BufferedWriter
*/
public void writeToFile(String filename) {
try
{
BufferedWriter bufferedWriter = null;
bufferedWriter = new BufferedWriter(new FileWriter(filename));
int i=1;
File f=new File("D:/Moviezzz");
File[] fi=f.listFiles();
for(File fil:fi)
{
if(fil.isHidden())
{
System.out.print("");
}
else if(fil.isDirectory()||fil.isFile())
{
int s=i++;
String files = fil.getName();
//Start writing to the output stream
bufferedWriter.write(s+" "+fil);
bufferedWriter.newLine();
// bufferedWriter.write(s+" "+files);
}
}
//Construct the BufferedWriter object
} catch (FileNotFoundException ex) {
ex.printStackTrace();
}catch (IOException ex) {
ex.printStackTrace();}
}
public static void main(String[] args) {
new Main().writeToFile("d://my.txt");
}
}
Uptil you call flush() method of BufferWriter class it will not write your data to file.
It is not necessary to flush() every time in a loop. But you can write it after your end of the loop.
Main thing to put that yourObj.flush() is to keep your buffer memory clean. as after call of that flush() method, data will be release from memory and written to your file.
Close the BufferedReader after the loop.
for(File fil:fi)
{
...
}
bufferedReader.close();
Also, I suggest these changes in your code to make it more readable and efficient:
BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(filename));
...
if(!fil.isHidden() && (fil.isDirectory() || fil.isFile()))
{
...
}
You can create the BufferedReaderdirectly. Then, you are getting the file name, but not doing anything with it, so just remove the get. And last, you don't have to have put System.out.print(""); in an if to check if the file is hidden. You can use an empty statement or even no code, or use the ! operator to invert.
if(fil.isHidden())
{
; // Do nothing
}
else
{
// Do something
}
if(fil.isHidden()); // Do nothing
else
{
// Do something
}
if(!fil.isHidden)
{
// Do something
}
I need to delete the contents of a file, before I write more information into it. I've tried different ways, such as where I delete the content but the file stays the same size, and when I start writing in it after the deletion, a blank hole appears to be the size of the deletion before my new data is written.
This is what I've tried...
BufferedWriter bw;
try {
bw = new BufferedWriter(new FileWriter(path));
bw.write("");
bw.close();
}
catch (IOException e) {
e.printStackTrace();
}
And I've also tried this...
File f = new File(file);
FileWriter fw;
try {
fw = new FileWriter(f,false);
fw.write("");
}
catch (IOException e) {
e.printStackTrace();
}
Can someone please help me with a solution to this problem.
FileWriter (path, false)
The false will tell the writer to truncate the file instead of appending to it.
Try calling flush() before calling close().
FileWriter writer = null;
try {
writer = ... // initialize a writer
writer.write("");
writer.flush(); // flush the stream
} catch (IOException e) {
// do something with exception
} finally {
if (writer != null) {
writer.close();
}
}
It might be because you are not closing the FileWriter, fw.close(); also you dont need to "delete" the old data, just start writing and it will overwrite the old data. So make sure you are closing everywhere.
This works for me:
File f=new File(file);
FileWriter fw;
try {
fw = new FileWriter(f);
fw.write("");
fw.close();
} catch (IOException e) {
e.printStackTrace();
}