注意点: 执行的代码文件所在盘为根目录即可。
假设 编译后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;
- }
- }