/**
*读取String
*/
FileReader fin=new FileReader("E:/Test.txt");
BufferedReader bf=new BufferedReader(fin);
String line;
while((line=bf.readLine())!=null){
System.out.println(line);
}
/**
*一个一个读
*/
public static void main(String[] args) {
try {
FileInputStream fis=new FileInputStream("E:/Test.txt");
InputStreamReader is=new InputStreamReader(fis,"UTF-8");//UTF-8,是文件的字符编码,换成你的文件的编码
int i=-1;
while((i=is.read())!=-1){
System.out.println((char)+i+"");
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
/*
* 读取String
*/
private String readtxt() throws IOException{
BufferedReader br=new BufferedReader(new FileReader("d:/sql.txt"));
String str="";
String r=br.readLine();
while(r!=null){
str+=r;
r=br.readLine();
}
return str;
}
/*
* 读取char
*/
private String readtxt2() throws IOException{
String str="";
FileReader fr=new FileReader("d:/sql.txt");
char[] chars=new char[1024];
int b=0;
while((b=fr.read(chars))!=-1){
str+=String.valueOf(chars);
}
return str;
}
/*
* 读取bytes
*/
private Byte[] readtxt3() throws IOException{
InputStream input=new FileInputStream("d:/sql.txt");
byte[] b=new byte[1024];
ArrayList lsbytes=new ArrayList();
int n=0;
while((n=input.read(b))!=-1){
for(int i=0;i<n;i++){
lsbytes.add(b[i]);
}
}
return (Byte[])(lsbytes.toArray());
}
Java读取txt文件
最新推荐文章于 2025-04-08 07:58:19 发布
本文介绍了几种使用Java进行文件读取的方法,包括按行读取字符串、逐字符读取及读取字节等不同方式,并提供了详细的代码示例。
4万+

被折叠的 条评论
为什么被折叠?



