无法读取简单的文本文件Java

时间:2014-12-03 19:29:49

标签: java text filenotfoundexception file-read

您好我被要求编写代码,该代码将读取与.class文件位于同一目录中的文本文件。我编写了一个简单的程序,它读取“input.text”并将其保存为字符串。

/** Import util for console input **/
import java.util.*;
import java.io.*;
/** Standard Public Declarations **/
public class costing
{
    public static void main(String[] args)
    {
        Scanner inFile = new Scanner(new FileReader("Coursework/input.txt"));
        String name = inFile.next();
        System.out.println(name);
    }
}

给出错误:

10: error: unreported expection FileNotFoundExcpetion; must be caught or declared to be thrown

我在同一个文件夹中尝试了input.txt,但是仍然没有运气。

谢谢!

4 个答案:

答案 0 :(得分:0)

你必须在代码中使用异常,将代码放在:

之间
try
{

  Scanner inFile = new Scanner(new FileReader("Coursework/input.txt"));

  String name = inFile.next();

  System.out.println(name);

}

catch( FileNotFoundExcpetion e)
{

}

答案 1 :(得分:0)

将代码置于 try ctach 中阻止代码:扫描程序inFile = new Scanner(新FileReader(“Coursework / input.txt”)); 会引发异常和玩具应该在编译代码之前处理它

答案 2 :(得分:0)

使用此代码段获取.class目录:

URL main = Main.class.getResource("Main.class");
  if (!"file".equalsIgnoreCase(main.getProtocol()))
  throw new IllegalStateException("Main class is not stored in a file.");
  File path = new File(main.getPath());
  Scanner inFile = new Scanner(new FileReader(path + "/input.txt"));
  String name = inFile.next();
  System.out.println(name);

更多信息here

答案 3 :(得分:0)

嗯,有两种类型的例外 - 未经检查和检查。 检查是在编译时检查的那些。所以,当编译器说 “10:错误:未报告的预期FileNotFoundExcpetion;必须被抓或宣布被抛出” 这意味着行inFile = new Scanner(new FileReader("input.txt"));抛出已检查的异常,这意味着此方法存在潜在的风险,它可以抛出FileNotFoundException,因此您应该处理它。因此,将代码包装在try / catch块中 -

/** Import util for console input **/
import java.util.*;
import java.io.*;
/** Standard Public Declarations **/
public class costing
{
 public static void main(String[] args)
 {

  Scanner inFile;
  try {
     inFile = new Scanner(new FileReader("Coursework/input.txt"));
     String name = inFile.next();
     System.out.println(name);
} catch (FileNotFoundException ex) {
    ex.printStackTrace();
}
}
}

如果在正确的目录中找不到input.txt,则可能会抛出运行时错误。