Win a copy of Think Java: How to Think Like a Computer Scientist this week in the Java in General forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

I/O question

 
Alex Mun
Greenhorn
Posts: 14
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Pie
Posts: 24211
35
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Alex Mun
Greenhorn
Posts: 14
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Well, I think I have to type the code again because everything is wrong.

Thanks.
 
Jon Parise
Ranch Hand
Posts: 81
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic