基本没太大差别
—2022.4.30更新—
打开文件经常需要抛出异常,但try
函数内部声明的成员又不能在函数外使用,try
catch
目前还没有学😓,干脆在类开头加上throws IOException
,避免了try
函数
Java BufferedReader class
read text from a character input stream.
belong to a java.io package.
public BufferedReader(Reader in)
Example
import java.io.*;
import java.util.Scanner;
public class OpenFileExample1 throws IOException{
BufferedReader reader = new BufferedReader(new FileReader("demo.txt"));
}
Java Scanner class
used for opening and reading a file
belongs to java.util package
public scanner (File source) throws FileNotFoundException
Example
import java.io.*;
import java.util.Scanner;
public class OpenFileExample2 throws IOException{
Scanner scanner = new Scanner(new FileReader("demo.txt"));
}
Java Desktop class
provide an open() method to open a file.
belongs to a java.awt package
have to check the operating system supports Desktop or not
public void open (File file) throws IOException
这个方案抛出好几种异常
- NullPointerException (文件为空)
- IllegalArgumentException(文件不存在)
- IOException(文件类型不支持)
- UnsupportedOperationExecution(当前平台不支持)
Example
import java.awt.Desktop;
import java.io.*;
public class OpenFileExample3{
public static void main(String[] args){
try{ //constructor of file class having file as argument
File file = new File("demo.txt");
if(!Desktop.isDesktopSupported()){
//check if Desktop is supported by Platform or not
System.out.println("not supported");
return;
}
Desktop desktop = Desktop.getDesktop();
if(file.exists())//checks file exists or not
desktop.open(file); //opens the specified file
}
catch(Exception e){
e.printStackTrace();
}
}
}
Java FileInputStream class
public FileInputStream(File file) throws FileNotFoundException
Example
import java.io.*;
import java.util.Scanner;
public class OpenFileExample4 throws IOException{
public static void main(String args[]){
FileInputStream fis = new FileInputStream("demo.txt");
char r = fis.read();
}
}
Java FileReader class
used for opening and reading a file.
belongs to a java.io package.
used for reading raw bytes using the FileInputStream class
public FileReader(File file) throws FileNotFoundException
Example
import java.io.*;
import java.util.Scanner;
public class OpenFileExample5 throws IOException{
FileReader fr=new FileReader("demo.txt");
char r = fr.read();
}