aspose file tools*
The moose likes Beginning Java and the fly likes I/O question Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "I/O question" Watch "I/O question" New topic
Author

I/O question

Alex Mun
Greenhorn

Joined: Oct 05, 2004
Posts: 14
Hi,

I'm trying to read a file in java but I can't due to an error. The code is:

import java.io.*;

class formato
{
public static void main(String args[])
{
try
{
FileReader fis = new FileReader("proveedores.txt");
}
catch (FileNotFoundException ex)
{
System.out.println("File not found");
return;
}
DataInputStream dis;
try
{
dis = new DataInputStream(dis);
}
catch (FileNotFoundException ex)
{
System.out.println("File not found");
}
}
}

When I compile this code I display two errors:

formato.java:22: variable dis might not have been initialized
dis = new DataInputStream(dis);
^
formato.java:24: exception java.io.FileNotFoundException is never thrown in body
of corresponding try statement
catch (FileNotFoundException ex)
^
2 errors

How I can solve them?

Thanks.
Ernest Friedman-Hill
author and iconoclast
Marshal

Joined: Jul 08, 2003
Posts: 24187
    
  34

Well, for the first one, you're passing "dis" as an argument to it's own constructor; and of course, it hasn't been initialized yet, no "might" about it. You intended to pass "fis", I imagine.

For the second one, the message is very straightforward. The DataInputStream constructor won't throw a FileNoteFoundException, so it's illegal to try to catch it.


[Jess in Action][AskingGoodQuestions]
Alex Mun
Greenhorn

Joined: Oct 05, 2004
Posts: 14
Well, I think I have to type the code again because everything is wrong.

Thanks.
Jon Parise
Ranch Hand

Joined: Jul 03, 2007
Posts: 81
You might not have to retype it all.

One problem I see is that you define things inside of try like this:



The problem is that with this code the fis Object only exists within the scope of the try statement. You won't be able to use it anywhere else. What you need to do is perhaps something like this:



Either that or you need to put all the code referring to fis inside of the try so it will still be in scope. Basically, anything you declare inside a pair of {} only exists inside them. Once you leave them it is gone. They call that scope.

Hope that helps a bit.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: I/O question