java读取文件内容

package cn.huwy.fileStream;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;


/**
*
* @author 胡巍译
* date :2014-02-12
*
*/
public class readTxtFile {

public String readFile (String filePath) {
String encoding = "UTF-8";
File file = new File(filePath);
StringBuffer stringBuffer = new StringBuffer();
try {
//判断文件是否存在
if (file.isFile() && file.exists()) {
InputStreamReader read = new InputStreamReader(new FileInputStream(file), encoding);
BufferedReader bufferedReader = new BufferedReader(read);
String lineTxt = null;
while ((lineTxt = bufferedReader.readLine()) != null ) {
stringBuffer.append(lineTxt);
}
read.close();
} else {
System.out.println("找不到指定的文件");
}

} catch (Exception e) {
// TODO: handle exception
System.out.println("读取文件内容出错");
e.printStackTrace();
}

return stringBuffer.toString();

}

public static void main(String[] args) {
readTxtFile readTxtFile = new readTxtFile();
String filePath = "D:\\json.txt";
String string = readTxtFile.readFile(filePath);
System.out.println("text:"+string);
}
}

你可能感兴趣的:(java读取文件)