【SC随笔】open and read txt file in java

—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();
}
  • 0
    点赞
  • 0
    收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
©️2022 CSDN 皮肤主题:数字20 设计师:CSDN官方博客 返回首页
评论

打赏作者

ClarifiedfishLEE

你的鼓励将是我创作的最大动力

¥2 ¥4 ¥6 ¥10 ¥20
输入1-500的整数
余额支付 (余额:-- )
扫码支付
扫码支付:¥2
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、C币套餐、付费专栏及课程。

余额充值