Simple PrintToFile program - java

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!");
}
}
}

There are a few problems here:
you need to close your output stream when you're done with output.close();
Your class needs a main method void main(String[] args that calls the output routine
The output routine needs to be enclosed in a method

output.close();
or
output.flush();
If you don't close your streams, they won't be saved to disk.

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();

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!");
}

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();
}

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");
}
}
}

you need to write output.close();

Related

BufferedWriter causes break

I'm trying to make a save function for a program I'm working on, and for some reason whenever I run it, it only gets past the first line of the try{} statement.
My code is as appears below.
public void saveGame() {
System.out.println("saveGame");
try
{
System.out.println("try saveGame");
BufferedWriter b = new BufferedWriter(new FileWriter("chardata.txt"));
System.out.println("try saveGame2");
String sp = System.getProperty("line.separator");
System.out.println("try saveGame3");
b.write("Miscellaneous char data here");
b.close();
}
catch(IOException ex)
{
System.out.println("File Writing Error");
}
}
When I run the program, the only lines that get printed are "saveGame" and "try saveGame." There is no "File Writing Error" either, it simply doesn't do anything after the "try saveGame" line. I'm not sure if this is relevant, but I am doing this from a computer at a school, which may have restricted permissions. Any kind of explanation and/or help would be much appreciated.
I think a better way to write your file would be using FileOutputStream and OutputStreamWriter.
Additionaly, you should move your b.close to a finally statement because if an exception is thrown before that b.close was executed, it never will be executed.
public void saveGame() {
System.out.println("saveGame");
try
{
System.out.println("try saveGame");
String path = "./chardata.txt"; //your file path
File file = new File(path);
FileOutputStream fsal = new FileOutputStream(file);
OutputStreamWriter osw = new OutputStreamWriter(fsal);
Writer w = new BufferedWriter(osw);
System.out.println("try saveGame2");
String sp = System.getProperty("line.separator");
System.out.println("try saveGame3");
w.write("Miscellaneous char data here");
}
catch(IOException ex)
{
System.out.println("File Writing Error");
}
finally{
if(w!=null)
w.close();
}
}

BufferedWriter not writing anything to a file

I am reading a file in.txt and writing the numbers to a file out.txt until 42 is found.But in out.txt I am getting blank file.Instead if I write System.out.println(num) instead of out.write(num) I get correct result.It means that the problem is with the statement of BufferedReader.Where I am wrong?
import java.io.*;
class Numbers
{
public static void main(String args[])
{
try{
String num;
BufferedReader in=new BufferedReader(new FileReader("in.txt"));
BufferedWriter out=new BufferedWriter(new FileWriter("out.txt"));
while((num=in.readLine())!=null)
{
if(Integer.parseInt(num)==42)
break;
else
out.write(num);
}
}catch(Exception e)
{
System.out.println("File not found");
}
}
}
The problem is the you are not closing the out stream. Change it to:
BufferedReader in = null;
BufferedReader out = null;
try{
String num;
in = new BufferedReader(new FileReader("in.txt"));
out = new BufferedWriter(new FileWriter("out.txt"));
while((num=in.readLine())!=null)
{
if(Integer.parseInt(num)==42)
break;
else
out.write(num);
}
out.close()
}catch(Exception e)
{
System.out.println("File not found");
}finally{
try{
if(in!=null) in.close();
if(out!=null) out.close();
}catch(Exception ex) {ex.printStackTrace();}
}
This is because, your OutputStream buffers your data and periodically flushes it. Closing the stream not only flushes it but also makes it safe for other applications to use the file.
In your case you might expect a weird behavior (with sometimes complete write and sometimes not). This is due to the fact that BufferedWriter() tries closing it in its finalize method (which may or may not be called)
You need to close your FileWriter:
while((num=in.readLine())!=null)
{
if(Integer.parseInt(num)==42)
break;
else{
out.write(num);
out.flush();
}
}
out.close();
Contents always need to be flushed. close() by itself will flush the stream for you, but it's good practice to flush() anyway.
You should close the stream after stop using it. Closing it will, firstly, flush the stream (all buffered data will be printed) and secondly, will release all resources the stream is using.
make sure you have out.close() at the end of try block.
if you have in.txt as a very big file, then you will see some data in out.txt.
BufferedWriter writes only when it has enough data to flush, which is approximately equal to one block size.

inside try block a FileIStream variable might not have been initialized error

I am trying to execute this code and I am also providing the valid argument but still I am getting error at line no. 34 and 35 that local variable fin and fout might not have been initialized. How to solve thisenter code here
package maxbj.myTest.p1;
import java.io.*;
public class CopyFile {
public static void main(String[] args)throws IOException {
int i;
FileInputStream fin;
FileOutputStream fout;
try{
//trying to open input file
try{
fin=new FileInputStream(args[0]);
}catch(FileNotFoundException e){
System.out.println("Input file not found");
return;
}
//trying to open output file
try{
fout=new FileOutputStream(args[1]);
return;
}catch(FileNotFoundException e){
System.out.println("Output file cannot be opened or created");
return;
}
}catch(ArrayIndexOutOfBoundsException e){
System.out.println("Array index out of bound exception");
}
//code to copy file
try{
do{
i=fin.read();
if(i!=-1) fout.write(i);
}while(i!=-1);
}catch(IOException e){
System.out.println("File Error");
}
fin.close();
fout.close();
}
}
PS- This code is from the book "JAVA COMPLETE REFRENCE"
The compiler is right (and the book is wrong, they should have tried compiling their code before publishing): there is a path through the code when fin remains uninitialized by the time the code reaches the fin.read() line.
Specifically, if ArrayIndexOutOfBoundsException gets thrown in the first outer try/catch block, the fin variable will not be assigned. Adding return to the outer catch block should fix this problem:
try {
...
} catch(ArrayIndexOutOfBoundsException e){
System.out.println("Array index out of bound exception");
return; // <<== Here
}
With the return statement in place, control will never reach the fin.read() unless fin has been initialized, fixing the compile-time error.
A simple way around this is to perform anything which requires fin and fout within the try block. This way you will never be trying to use the streams when they have failed on opening.
try
{
fout = new FileOutputStream(...);
fin = new FileInputStream(...);
// Code goes here
fout.close();
fin.close();
}
catch(FileNotFoundException e)
{
// Error code - e should contain the file name/path
}
Also, it is always good practice to initialise variables when you declare them:
FileOutputStream fout = null;
FileInputStream fin = null;
However, this way (just initialising to null) you programming logic will not cause compiler errors, but if not handled correctly you may get NullPointerExceptions if you try block throws.

Stream Object Initialization

Now I am getting compile time error at line 30 and 38 that 'fin' might not have been initialized. but its perfectly to write it this way
import java.io.*;
class CopyFile {
public static void main(String args[]) throws IOException {
int i;
FileInputStream fin;//can't it be done like this?
FileOutputStream fout= new FileOutputStream(args[1]);
try{
//open input file
try{
fin = new FileInputStream(args[0]);
}
catch(FileNotFoundException e){
System.out.println("Input file Not Found");
return;
}
//open output file
try{
fout = new FileOutputStream(args[1]);
}
catch(FileNotFoundException e){
System.out.println("Error Opening File");
}
}
catch(ArrayIndexOutOfBoundsException e){
System.out.println("usage: Copyfile From to");
}
try{
do{
i = fin.read();
if(i!= -1)
fout.write(i);
}while(i != -1);
}
catch(IOException e){
System.out.println("file error");
}
fin.close();
fout.close();
}
}
I have seen it many time initialized like this. I think its due to the try blocks.
it might miss the initialization due to being in the try block and hence the error?
The problem is that you're not initializing the FileInputStream fin at all. Your code will look like this to the compiler:
FileInputStream fin;
try {
fin = ...
//more code goes here...
} catch (...) {
//exception handling...
} finally {
fin.close(); //fin is not even null for the compiler
}
In order to make the code work, initialize it at least with a null value and check if fin != null before using the close method.
FileInputStream fin = null;
try {
fin = ...
//more code goes here...
} catch (...) {
//exception handling...
} finally {
if (fin != null) {
fin.close(); //fin is not null, at least the JVM could close it
}
}
More info:
Java: Declaring Variables
Uninitialized variables and members in Java
FileInputStream fin=null;
Assign it null or FileInputStream object.
Local variable need to be assigned to some value before being used.
Though in the first try block, you are initializing fin as fin = new FileInputStream(args[0]);, your nested statements confuse the compiler. Just update your declaration as below:
FileInputStream fin = null;
Dont use try catch for an if and vice versa.
Try/catch is for when things go wrong behind your control and that is no part of normal program flow for example writing to a hard disk that is full....
Use if for normal error checking
In your example check your args array with an if block and then initialize your fin.

Android:Text after line break is not visible in a file(PrintWriter)

I am using PrintWriter to print some characters into the file. But when I use Println() to print a new line, the characters after new line are not visible.
Following is my code snippet
public void writeData(String data)
{
//PrintWriter csvWriter;
try
{
csvWriter = new PrintWriter(new FileWriter(file,true));
csvWriter.print(data+","+"hello");
//csvWriter.print("\r\n");
csvWriter.println();
csvWriter.print("world");
csvWriter.close();
}
catch (Exception e)
{
e.printStackTrace();
}
}
So in my file only the data & hello is visible. But "world" is not visible. I tried to print the new line using "\r\n" & "\n". But nothing is working.
Somebody please help me....Thanks!
try this:
csvWriter.println(System.getProperty("line.separator"));
Try using ... Line Seperator from system class
System.get("line.separator")
You have to flush data.
csvWriter.println();
csvWriter.print("world");
//writes data from buffer to stream
csvWriter.flush();
csvWriter.close();
try {
// open myfilename.txt for writing
OutputStreamWriter out = new OutputStreamWriter(FileOutputStream("myfilename.txt",0));
// write the contents on mySettings to the file
out.write("Hello \n World");
// close the file
out.close();
} catch (java.io.IOException e) {
//do something if an IOException occurs.
}

Categories

Resources