无法读取简单的Java文本文件
大家好,我被要求编写代码来读取与.class文件位于同一目录中的文本文件。我编写了一个简单的程序,读取“input.text”并将其保存为字符串无法读取简单的Java文本文件,java,text,filenotfoundexception,file-read,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
/** 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
,但仍然没有成功
谢谢 您必须在代码中使用一个exeption,将代码放在以下两个位置之间:
try
{
Scanner inFile = new Scanner(new FileReader("Coursework/input.txt"));
String name = inFile.next();
System.out.println(name);
}
catch( FileNotFoundExcpetion e)
{
}
将您的代码放入try ctach阻止代码:Scanner infle=new Scanner(new FileReader(“Coursework/input.txt”)会引发异常,toy应该在编译代码之前处理该异常使用此代码段获取.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);
更多信息。嗯,有两种类型的异常-未检查和已检查。 checked是在编译时检查的。所以,当编译器说 “10:错误:未报告的expection
FileNotFoundException
;必须捕获或声明为抛出”
这意味着lineinfle=newscanner(newfilereader(“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,它可能会引发运行时错误。在try/catch块中包围您的Scanner类。。感谢您的回复,此返回“error not find symbol catch(FileNotFoundException e)”谢谢您的帮助,我也理解了发生这种情况的原因,这很有用:)