Java相对路径如何读取文件呢?
下文笔者讲述java代码使用相对路径读取文件的方法及示例分享,如下所示
相对路径读取的实现思路
如: File f = new File("src/com/java265/res/a.txt"); File f = new File("doc/b.txt"); 注意事项: 路径不以“/”开头
使用CLASSPATH读取包内文件
读取包内文件 使用的路径一定是相对classpath路径 如: InputStream in = ReadFile.class.getResourceAsStream("/com/java265/res/a.txt"); 注意事项: 此处必须使用 斜杠 开头例:java读取文件的示例代码
package com.java265.test; import java.io.*; /** * Java读取相对路径的文件 * */ public class ReadFile { public static void main(String[] args) { readTextA_ByClassPath(); readTextA_ByProjectRelativePath(); readTextB_ByProjectRelativePath(); } /** * 通过工程相对路径读取(包内)文件,注意不以“/”开头 */ public static void readTextA_ByProjectRelativePath() { System.out.println("-----------------readTextA_ByProjectRelativePath---------------------"); File f = new File("src/com/java265/res/a.txt"); String a = file2String(f, "GBK"); System.out.println(a); } /** * 通过工程相对路径读取(包外)文件,注意不以“/”开头 */ public static void readTextB_ByProjectRelativePath() { System.out.println("-----------------readTextB_ByProjectRelativePath---------------------"); File f = new File("doc/b.txt"); String b = file2String(f, "GBK"); System.out.println(b); } /** * 通过CLASSPATH读取包内文件,注意以“/”开头 */ public static void readTextA_ByClassPath() { System.out.println("-----------------readTextA_ByClassPath---------------------"); InputStream in = ReadFile.class.getResourceAsStream("/com/java265/res/a.txt"); String a = stream2String(in, "GBK"); System.out.println(a); } /** * 文件转换为字符串 * * @param f 文件 * @param charset 文件的字符集 * @return 文件内容 */ public static String file2String(File f, String charset) { String result = null; try { result = stream2String(new FileInputStream(f), charset); } catch (FileNotFoundException e) { e.printStackTrace(); } return result; } /** * 文件转换为字符串 * * @param in 字节流 * @param charset 文件的字符集 * @return 文件内容 */ public static String stream2String(InputStream in, String charset) { StringBuffer sb = new StringBuffer(); try { Reader r = new InputStreamReader(in, charset); int length = 0; for (char[] c = new char[1024]; (length = r.read(c)) != -1;) { sb.append(c, 0, length); } r.close(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return sb.toString(); } }
读取CLASSPATH下文件的绝对路径
package com.java265; import java.io.File; /** * CLASSPATH文件的绝对路径获取测试 */ public class Test { //classpath的文件路径 private static String cp = "/com/java265/cfg/syscfg.properties"; public static void main(String[] args) { //当前类的绝对路径 System.out.println(Test.class.getResource("/").getFile()); //指定CLASSPATH文件的绝对路径 System.out.println(Test.class.getResource(cp).getFile()); //指定CLASSPATH文件的绝对路径 File f = new File(Test.class.getResource(cp).getFile()); System.out.println(f.getPath()); } }
版权声明
本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。