两种读取文件的java方法
Two way for reading the files in java.
one,we don't need to know what is file's encoding
一个不用知道文件的编码
another,we must know the file's encoding before we read this file
另外一个,必须在读取之前知道文件编码
package com.javaer.examples.file;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
public class ReadingFile {
/**
* we don't need to know what is file's encoding
* @param path file path
* @return a string in the file
* @throws IOException
*/
public static String readFile(String path) throws IOException {
BufferedReader input = new BufferedReader(new FileReader(path));
String line = null;
StringBuffer sb = new StringBuffer();
while ((line = input.readLine()) != null) {
sb.append(line);
sb.append(System.getProperty("line.separator"));
}
input.close();
return sb.toString();
}
/**
* we must know the file's encoding before we read this file
* @param path file path
* @param encode the file's encode
* @return a string in the file
* @throws IOException
*/
public static String readFileEncoding(String path, String encode)
throws IOException {
InputStream r = new FileInputStream(path);
ByteArrayOutputStream byteout = new ByteArrayOutputStream();
byte tmp[] = new byte[256];
byte context[];
int i = 0;
while ((i = r.read(tmp)) > 0) {
byteout.write(tmp, 0, i);
}
context = byteout.toByteArray();
String str = new String(context, encode);
r.close();
byteout.close();
return str;
}
/**
* @param args
*/
public static void main(String[] args) {
String s = null;
try {
s = ReadingFile.readFile("E:/1.txt");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(s);
try {
s = ReadingFile.readFileEncoding("E:/2.txt","UTF-8");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(s);
}
}