The book I'm using says it should look something like this

import java.io.*;

public class main
{
	public static void main(String[] argv)
	{
		String fil = "CormeOn.bat";
		
		FileWriter fw = null;
		try {
			fw = new FileWriter(fil);
			}
		
		catch(FileNotFoundException fnf)
			{
			System.out.println("Yea...."+fnf);
			}
		
		catch (IOException e)
			{
			e.printStackTrace();
			}
		

		
		
		BufferedWriter bw = new BufferedWriter(fw);
		PrintWriter utFil = new PrintWriter(bw);
		
		utFil.print("@echo off");
		utFil.println("ping google.com");
		utFil.println();
		utFil.print("echo woop-da-woop");
		
		utFil.close();
		
	}
}

1. Is this way outdated or is there a better way to write to/from files?

2. What does it mean when you write throws IOException after the main(...) here {...}?
The try-catch isn't needed then it seems.

3. If the file doesnt exist, it creates it. So how do you use FileNotFoundException..?

4. Why is it good to use a bufferedwriter and how does it work? I mean, you never directly use it?

Some website showed an example with BufferedWriterVariable.write

Recommended Answers

All 3 Replies

1. The way you do it in your piece of code will work. I like FileOutputSteam better:

public class MyFirstFileWritingApp
{
	// Main method
	public static void main (String args[])
	{
		// Stream to write file
		FileOutputStream fout;		

		try
		{
		    // Open an output stream
		    fout = new FileOutputStream ("myfile.txt");

		    // Print a line of text
		    new PrintStream(fout).println ("hello world!");

		    // Close our output stream
		    fout.close();		
		}
		// Catches any error conditions
		catch (IOException e)
		{
			System.err.println ("Unable to write to file");
			System.exit(-1);
		}
	}	
}

From: http://www.javacoffeebreak.com/faq/faq0004.html

2. You are right, the try catch is not needed for the IOException. If the method you are trying to excecute also throws a FileNotFoundException, you should catch that.

3.

This exception will be thrown by the FileInputStream, FileOutputStream, and RandomAccessFile constructors when a file with the specified pathname does not exist. It will also be thrown by these constructors if the file does exist but for some reason is inaccessible, for example when an attempt is made to open a read-only file for writing.

From: http://download.oracle.com/javase/1.4.2/docs/api/java/io/FileNotFoundException.html

4. I don't think you have to use it, look at answer 1. I like to use a FileOutputSteam, with a PrintStream. It's easy, and doesn't require a lot of code.

1. The way you do it in your piece of code will work. I like FileOutputSteam better:

public class MyFirstFileWritingApp
{
	// Main method
	public static void main (String args[])
	{
		// Stream to write file
		FileOutputStream fout;		

		try
		{
		    // Open an output stream
		    fout = new FileOutputStream ("myfile.txt");

		    // Print a line of text
		    new PrintStream(fout).println ("hello world!");

		    // Close our output stream
		    fout.close();		
		}
		// Catches any error conditions
		catch (IOException e)
		{
			System.err.println ("Unable to write to file");
			System.exit(-1);
		}
	}	
}

From: http://www.javacoffeebreak.com/faq/faq0004.html

2. You are right, the try catch is not needed for the IOException. If the method you are trying to excecute also throws a FileNotFoundException, you should catch that.

3.
From: http://download.oracle.com/javase/1.4.2/docs/api/java/io/FileNotFoundException.html

4. I don't think you have to use it, look at answer 1. I like to use a FileOutputSteam, with a PrintStream. It's easy, and doesn't require a lot of code.

About #2
What I meant was, if I wrote

FileWriter fw = null;

try {

fw = new FileWriter(fil);

}

 

catch(FileNotFoundException fnf)

{

System.out.println("Yea...."+fnf);

}

 
/*
catch (IOException e)

{

e.printStackTrace();

}
*/

It would complain that IOExceptions were not handled.

That part catches any IOExceptions and then does whatever you write between the {}
But what does the "...main(String[] argv) throws IOException{...}" do?
If it gets an IOException it doesn't care and just "throws" it away?

And about writing to files.
The book said the buffer is good because then you don't have to constantly get/write characters into the file but put them in a buffer kinda and get/send info from buffer every now and then.

the FileOutPutStream doesnt do that?


If you try to open a stream to a file, and that file doesn't exist, it creates the file, no?
So how could it throw an FileNotFoundException?

FileOutputStream is not buffered, so each time you write a few bytes to it Java writes them to the file (although the operating system will probably do its own buffering). For real-word-sized applications you would normally wrap it in a buffered stream for performance reasons like your book said.

If you call a method that can throw an IOException then you must do one of these two things:
1. put the call in a try, with a catch that catches IOException (or one of its superclasses, eg Exception) or
2. declare your own method as "throws IOException" - which means that whoever calls your method will have to chose option 1 or 2 in their method.
If your method is the main(String[] args) method and it's declared to throw IOException, then the Java runtime will handle the exception by terminating your program and displaying the exception as an error message.

Exceptions are just Java classes, and are documented in the API documentation in the usual way - for example

public class FileNotFoundException
extends IOException

Signals that an attempt to open the file denoted by a specified pathname has failed.

This exception will be thrown by the FileInputStream, FileOutputStream, and RandomAccessFile constructors when a file with the specified pathname does not exist. It will also be thrown by these constructors if the file does exist but for some reason is inaccessible, for example when an attempt is made to open a read-only file for writing.

Also, the documentation for FileOutputStream's constructor says

If the file exists but is a directory rather than a regular file, does not exist but cannot be created, or cannot be opened for any other reason then a FileNotFoundException is thrown.

- which answers your last question

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.