栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

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

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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

基本没太大差别
  • Java BufferedReader class
    • Example
  • Java Scanner class
    • Example
  • Java Desktop class
    • Example
  • Java FileInputStream class
    • Example
  • Java FileReader class
    • Example

—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();
}
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/845883.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号