您的位置:首页 > 编程语言 > Java开发

java读取文件的方法总结

2008-09-28 10:30 465 查看
java的读取文件包括读取字符流和字节流两种,都可以用到buffer缓存。按读取的文件类型可以分为本地文件和网络资源。

各种读取方式个有各自的优点,下面是我对java读取文件方法的总结。

读取本地文件

四种读取方式

java文件名为CommFile.java

//读取本地绝对路径的文件

public static List readFileToList(String FilePath)
throws IOException {

//FilePath 完整文件路径
FileReader fr= new FileReader(FilePath);

// FileReader不能指定文件编码格式,用系统默认的编码格式解码。
String record = "";
List content = new ArrayList();
int recCount = 0;
BufferedReader br = new BufferedReader(fr);

while ((record = br.readLine()) != null) {
recCount++;
content.add(record.trim());
}
fr.close();
br.close();
return content;
}

//读取工程相对路径的文件

public static List readFileToList2(String path)
throws IOException {
//getResourceAsStream将文件读入缓存,无法重新加载文件。
InputStream is = CommFile.class.getResourceAsStream(path);
InputStreamReader isr = new InputStreamReader(is,"utf-8");
BufferedReader br = new BufferedReader(isr);

String record = "";
List content = new ArrayList();
while ((record = br.readLine()) != null) {
content.add(record.trim());
}
isr.close();
br.close();
return content;
}

public static String readFileToString3(String path)
throws IOException {//工程相对路径
String filepath = CommFile.class.getResource(path).getFile();
FileReader fr= new FileReader(filepath);
String record = "";
StringBuffer sb = new StringBuffer();
int recCount = 0;
BufferedReader br = new BufferedReader(fr);

while ((record = br.readLine()) != null) {
recCount++;
sb.append(record.trim());
}
fr.close();
br.close();
return sb.toString() ;
}

public static String readFileToString4(String path)
throws IOException {//工程相对路径
String filepath = CommFile.class.getResource(path).getFile();
InputStream is = new FileInputStream(filepath);
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String record = "";
StringBuffer sb = new StringBuffer();
int recCount = 0;

while ((record = br.readLine()) != null) {
recCount++;
sb.append(record.trim());
}
isr.close();
br.close();
return sb.toString() ;
}

读取网络资源
public static String readWebFile(String url,String code)
throws IOException{
URL path = new URL(url);
InputStream is = path.openStream() ;
InputStreamReader isr = new InputStreamReader(is,code);
BufferedReader br = new BufferedReader(isr);
StringBuffer sb = new StringBuffer() ;
String s = "" ;
while((s=br.readLine())!=null){
sb.append(s) ;
}
return sb.toString() ;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: