954,545 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

basic file i/o

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

jaden403
Newbie Poster
17 posts since May 2006
Reputation Points: 10
Solved Threads: 0
 

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

masijade
Industrious Poster
Moderator
4,253 posts since Feb 2006
Reputation Points: 1,471
Solved Threads: 494
 

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

jaden403
Newbie Poster
17 posts since May 2006
Reputation Points: 10
Solved Threads: 0
 

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.

masijade
Industrious Poster
Moderator
4,253 posts since Feb 2006
Reputation Points: 1,471
Solved Threads: 494
 

Okay, thanks...

jaden403
Newbie Poster
17 posts since May 2006
Reputation Points: 10
Solved Threads: 0
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You