Reputation: 57
I'm trying to write a simple java program in Eclipse that prints these four lines into a file "hello.txt". THe problem is, that nothing is happening, it doesn't create a new file, and if i make a file called "hello.txt" the program doesn't overwrite it. What am I doing wrong? Thanks for your answers. :)
import java.io.*;
public class output {
{
try{
PrintStream output = new PrintStream(new File("hello.txt"));
output.println("Hello World!");
output.println("this is ");
output.println("four lines of");
output.println("text.");
}catch(FileNotFoundException e){
System.out.println("Cannot write file!");
}
}
}
Upvotes: 0
Views: 583
Reputation: 1507
The right way to do it is like this
import java.io.*;
class PrintStreamDemo {
public static void main(String args[]){
FileOutputStream out;
PrintStream ps; // declare a print stream object
try {
// Create a new file output stream
out = new FileOutputStream("myfile.txt");
// Connect print stream to the output stream
ps = new PrintStream(out);
ps.println ("This data is written to a file:");
System.err.println ("Write successfully");
ps.close();
} catch (Exception e){
System.err.println ("Error in writing to file");
}
}
}
Upvotes: 0
Reputation: 11
output.close();
or
output.flush();
If you don't close your streams, they won't be saved to disk.
Upvotes: 1
Reputation:
At first you have to create your file if it is not there. With that you create the PrintStream-Object and write the content you like in it. Finally don't forget to flush and close the stream.
try{
File f = new File("C:/hello.txt");
if (!f.exists()){
f.createNewFile();
}
PrintStream output = new PrintStream(f);
output.println("Hello World!");
output.println("this is ");
output.println("four lines of");
output.println("text.");
output.flush();
output.close();
}catch(FileNotFoundException e){
System.out.println("Fil kan ikke skrives!");
} catch (IOException e) {
e.printStackTrace();
}
Upvotes: 0
Reputation: 4015
I just run your code on windows putting it in main method and it works (it creates the file). try with an absolute path, perhaps you are checking the wrong directory. You also should call
output.close();
Upvotes: 0
Reputation: 23171
There are a few problems here:
output.close();
void main(String[] args
that calls the output routineUpvotes: 2
Reputation: 4288
you should add output.close();
try{
PrintStream output = new PrintStream(new File("hello.txt"));
output.println("Hello World!");
output.println("this is ");
output.println("four lines of");
output.println("text.");
output.close();
}catch(FileNotFoundException e){
System.out.println("Cannot write file!");
}
Upvotes: 0