Quantcast
Channel: Programming Forums
Viewing all articles
Browse latest Browse all 51036

writing to a file problem

$
0
0
i have this ode from my lecture as a example to show us how to write to a file
import java.io.*;   // for PrintWriter class

import java.util.* ; // for Scanner  class

public class TestFileWrite
{
   public static void main(String[] args) 
  {
		 PrintWriter output = null;
		 Scanner  scanner = null;
		
		File confidential = new File("secrets.txt");
		
		 // check that the file doesn't already exist, cos' otherwise writing to it would overwrite any existing content
		if (!confidential.exists())	// file doesn't exist
		{
			try 
			{
				output = new PrintWriter(confidential);	// create new stream, link newly created stream to  file
			}
			catch (FileNotFoundException e)	// problem with file !
			{ 
   				System.out.println("Error 	 problem creating the file! Program closing");
   				System.exit(0);  // this terminates the program - parameter 0 indicates normal termination
			}
        	
			//file opened OK, so proceed
			scanner = new Scanner(System.in);
			System.out.println("Student names and exam marks, use CNTL Z to end");
		
		
			// reading data from scanner could throw InputMisMatchException
			// but this is not checked. 
		
			while( scanner.hasNext())  // while there is more input for the Scanner
			{
				String name = scanner.next();
				int mark = scanner.nextInt();
				output.println( name + " " + mark);	// write data to file specified by output
			}
			
			// tidy up and close the file
		 	output.close();
		}
		
		else 	// file already exists, prevent overwriting
		{
			System.out.println("The file already exists, program is closing");
		}
		
 }
}
	



but when i compile it i get a error so i am stuck

ay help is appreciated
thanks
dale

Viewing all articles
Browse latest Browse all 51036

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>