注意点: 执行的代码文件所在盘为根目录即可。
假设 编译后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;
}
}
本文介绍了一种在Windows和Linux环境下编写代码时处理文件路径的方法,使得代码可以在不同操作系统间无缝迁移。通过将绝对路径设置为以根目录开始,可以避免因操作系统差异导致的路径问题。
778

被折叠的 条评论
为什么被折叠?



