注意點: 執行的代碼檔案所在盤為根目錄即可。
假設 編譯後class檔案在e盤,則e下的 E:\opt\test.txt 在代碼中就可以寫成/opt/test.txt
這樣的好處是 windows下寫的代碼直接部署到linux伺服器就可以了,路徑不用改。
測試代碼:
package com.yanek.util;import java.io.BufferedReader;import java.io.File;import java.io.FileReader;import java.io.IOException;public class Test {/** * @param args */public static void main(String[] args) {String path="/opt/test.txt";String c=readText(path);System.out.println("c="+c);}/** * 從檔案讀取內容 * * @param filename * @return */public static String readText(String filename) {String content = "";try {File file = new File(filename);if (file.exists()) {FileReader fr = new FileReader(file);BufferedReader br = new BufferedReader(fr);String str = "";String newline = "";while ((str = br.readLine()) != null) {content += newline + str;newline = "\n";}br.close();fr.close();}} catch (IOException e) {e.printStackTrace();}return content;}}