如何解决此错误?我尝试使用throws
到throw
FileNotFoundException
,但仍然是相同的错误。
编译时错误:“默认构造函数无法处理异常类型隐式超级构造函数引发的异常。必须定义一个显式构造函数”
代码:
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;
public class FileOne {
Scanner sc = new Scanner(System.in);
String file_name = sc.nextLine();
File obj = new File(file_name);
Scanner reader_obj = new Scanner(obj); // <--- error in this line
public static void main(String args[]) {
FileOne f = new FileOne();
f.create();
f.writeFile();
f.readFile();
}
void create() {
try {
System.out.println("Enter a file name");
if (obj.createNewFile()) {
System.out.println("file name is" + obj.getName());
} else {
System.out.println("Already exists");
}
} catch (IOException e) {
System.out.println("error occured while creating");
}
}
//method to write in file
void writeFile() {
try {
FileWriter w = new FileWriter(obj);
w.write("Learning files now");
w.close();
} catch (IOException e) {
System.out.println("Exception occured while writing a file");
}
}
//method to read
/* use the Scanner class to read the contents of the text file created */
void readFile() {
while (reader_obj.hasNextLine()) {
String data = reader_obj.nextLine();
System.out.println(data);
}
reader_obj.close();
}
}
答案 0 :(得分:1)
默认构造函数隐式调用的行Scanner reader_obj=new Scanner(obj);
可能抛出FileNotFoundException
,这是一个已检查的异常,必须对其进行处理。
一种方法是显式定义一个无参数构造函数:
public FileOne() throws FileNotFoundException {
}
尽管,如果要这样做,您应该考虑将成员的初始化移入其中。
答案 1 :(得分:1)
已解决的错误:
throws
在main()
和reading()
方法中引发异常。FileReader
类从给定的输入文件中读取数据最终密码:
public class FileOne {
Scanner sc=new Scanner(System.in);
String file_name=sc.nextLine();
File obj=new File(file_name);
//method for creating a file
void create(){
try{
if(obj.createNewFile()){
System.out.println("file name is"+obj.getName());
}
else{
System.out.println("Already exists");
}
}
catch(IOException e){
System.out.println("error occured while creating");
}
}
//method to write in file
void writeFile(){
try{
FileWriter w=new FileWriter(obj);
w.write("Learning files now");
w.close();
}
catch(IOException e){
System.out.println("Exception occured while writing a file");
}
}
void reading() throws FileNotFoundException,IOException{
FileReader reader=new FileReader(file_name);
int i;
while((i=reader.read())!=-1){
System.out.print((char)i);
}
reader.close();
}
public static void main(String args[])throws FileNotFoundException,IOException{
FileOne f=new FileOne();
f.create();
f.writeFile();
f.reading();
}
}
答案 2 :(得分:0)
添加如下构造函数:
public FileOne () throws FileNotFoundException {
}
按如下所示编辑void main ()
(您还需要从main抛出异常):
public static void main(String args[]) throws FileNotFoundException {
FileOne f = new FileOne();
f.create();
f.writeFile();
f.readFile();
}