1. 程式人生 > >讀取txt單行內容

讀取txt單行內容

/**
* 讀取web專案txt裡的單行內容
* @param fileP 檔名稱
*/
public static String readTxtFile(String fileP) {
try {

String filePath = String.valueOf(Thread.currentThread().getContextClassLoader().getResource("")); //專案路徑
filePath = filePath.replaceAll("file:/", "");
filePath = filePath.replaceAll("%20", " ");
filePath = filePath.trim() + fileP.trim();
if(filePath.indexOf(":") != 1){
filePath = File.separator + filePath;
}
String encoding = "utf-8";
File file = new File(filePath);
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) {
System.out.println(lineTxt);
return lineTxt;
}
read.close();
}else{
System.out.println("找不到指定的檔案,檢視此路徑是否正確:"+filePath);
}
} catch (Exception e) {
System.out.println("讀取檔案內容出錯");
}
return "";
}