在D盘下新建一个文本文件in.txt,路径为(D:\\in.txt),在里面写入一些字符
1.按字符读取文件
package 文件读取;
/**
* 功能:按字符读取文件
* 时间:2011.6.1 23.33
*/
import java.io.*;
public class 按字符读取文件 {
public static void main(String[] args){
//File f = new File("D:\\io.txt");
FileReader fr = null;
try {
fr = new FileReader("D:\\in.txt");
int n = 0;
char[] c = new char[1024];
while((n=fr.read(c))!=-1){
System.out.println(c);
String s = new String(c,0,n);
System.out.println(s);
}
} catch (Exception e) {
e.printStackTrace();
}finally{
try {
fr.close();
} catch (Exception e2) {
e2.printStackTrace();
}
}
}
}
2.按字节读取文件
package 文件读取;
import java.io.*;
public class 按字节读取文件 {
public static void main(String[] args){
FileInputStream fis = null;
try {
File f = new File("D:\\in.txt");
fis = new FileInputStream(f);
byte[] b = new byte[1024];
int n = 0;
while((n=fis.read(b,0,1024))!=-1){
String s = new String(b,0,n);
System.out.println(s);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
3.缓冲读取文件
package 文件读取;
/*
* 缓冲读取
* */
import java.io.*;
public class 缓冲读取文件 {
public static void main(String[] args){
BufferedReader br = null;
try {
FileReader fr = new FileReader("D:\\in.txt");
br = new BufferedReader(fr);
String s = "";
while((s=br.readLine())!=null){
System.out.print(s);
}
} catch (Exception e) {
e.printStackTrace();
}
//FileReader fr = new FileReader("D:\\test.txt");
}
}