注意点: 执行的代码文件所在盘为根目录即可。
假设 编译后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;
- }
- }
本文介绍了一种在Java中处理文件路径的方法,使得代码可以在Windows和Linux等不同操作系统上无缝运行,无需修改路径配置。通过将实际的磁盘路径转换为统一的格式,实现了代码的高度可移植性。
5万+

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



