package com.zhaoxueer.program;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
public class ReadJavaFile {
/**
*
* <p>TODO(按行读文件)</p>
* @author 276283
* @date 2016-1-26 上午9:42:48
* @param fileName
* @see
*/
public void readFile(String fileName){
BufferedReader reader = null;
String content = null;
try {
reader = new BufferedReader(new FileReader(fileName));
while(null != (content = reader.readLine() )){
System.out.println(content);
}
}catch (FileNotFoundException e) {
e.printStackTrace();
}catch (IOException e) {
e.printStackTrace();
}finally{
if(reader != null){
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
/**
*
* <p>TODO(按字节读文件)</p>
* @author 276283
* @date 2016-1-26 上午9:43:02
* @param pathName
* @see
*/
public void readFileByBytes(String fileName){
InputStream is = null;
File file = new File(fileName);
int tempByte;
try {
is = new FileInputStream(file);
while((tempByte = is.read()) != -1){
System.out.write(tempByte);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if(is != null){
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
/**
*
* <p>TODO(按字符读取文件)</p>
* @author 276283
* @date 2016-1-26 上午9:43:46
* @see
*/
public void readFileByChar(String fileName){
File file = new File(fileName);
Reader reader = null;
int tempChar;
try {
reader = new InputStreamReader(new FileInputStream(file));
while(-1 != (tempChar = reader.read())){
System.out.print((char)tempChar);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if(reader != null){
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
public static void main(String[] args) {
ReadJavaFile readJavaFile = new ReadJavaFile();
System.out.println("---------------------------- 按行读文件开始(BufferedReader) --------------------------");
readJavaFile.readFile("E:/myJava/Hello.java");
System.out.println("---------------------------- 按行读文件结束(BufferedReader) --------------------------");
System.out.println("--------------------------- 按字节读文件开始(FileInputStream) ------------------------");
readJavaFile.readFileByBytes("E:/myJava/Hello.java");
System.out.println("--------------------------- 按字节读文件结束(FileInputStream) ------------------------");
System.out.println("--------------------------- 按字符读文件开始(InputStreamReader) ------------------------");
readJavaFile.readFileByChar("E:/myJava/Hello.java");
System.out.println("--------------------------- 按字符读文件结束(InputStreamReader) ------------------------");
}
}
Java读取文件内容的三种方式
最新推荐文章于 2023-06-13 11:25:45 发布