【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
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值