I have a basic Java file I/O question. I am trying to read/write from/to a text file (obviously) from within a function that is called by main(). Can you do the following within a function:

Scanner inFile = new Scanner(new FileReader("File1.txt"));
PrintWriter outFile = new PrintWriter("File2.txt");

or does this have to be done within main()? If within main(), then how do you get inFile and outFile to work in the function? Do you pass them like a normal parameter?

I tried creating the inFile and outFile objects within a function, but kept getting errors when the program compiled. Thanks...

Jaden403

Recommended Answers

All 4 Replies

Yes, of course you can. What are the errors you are getting?

The first example works fine:

import java.io.*;
import java.util.*;
public class File
{   
   public static void main(String[] args) throws FileNotFoundException 
   { 
     PrintWriter outFile = new PrintWriter(new PrintWriter("outputdocument.txt"));
 
   for (int i = 1; i <= 10; i++)
     outFile.printf("%d%n", i);
 
   outFile.close();
   }
}

However, when I try to do the same thing in a function:

import java.io.*;
import java.util.*;
public class File2
{   
   public static void main(String[] args) 
   { 
       printFunction();
   }
 
  public static void printFunction() throws FileNotFoundException 
  {
     PrintWriter outFile = new PrintWriter(new PrintWriter("outputdocument.txt"));
 
    for (int i = 1; i <= 10; i++)
      outFile.printf("%d%n", i);
 
    outFile.close(); 
  }
}

I get this message:
File2.java:14: unreported exception java.io.FileNotFoundException; must be caught or declared to be thrown
PrintWriter outFile = new PrintWriter(new PrintWriter("outputdocument.txt"));
^
1 error

Well, the error says it all.

Your method delares that it throws an exception. That means, that you must either call the method from within a try catch block, or the method (this time main) calling your method, must also declare that it throws the same exception that your method does.

Okay, thanks...

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.