标签:
通常情况下,在Java项目中,我们使用的路径都是在拿到类加载路径后,根据相对位置,使用
package com.rock.test.filePath; import java.io.BufferedReader; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; public class FilePathTest { public static void main(String[] args) { //使用文件相对路径 File file1 = new File("test1.txt"); System.out.println("test1.txt exists " + file1.exists()); File file2 = new File("src\\test2.txt"); System.out.println("test2.txt exists " + file2.exists()); File file3 = new File("src\\com\\rock\\test\\filePath\\test3.txt"); System.out.println("test3.txt exists " + file3.exists()); InputStream stream = FilePathTest.class.getResourceAsStream("/test2.txt"); // InputStream stream = FilePathTest.class.getResourceAsStream("test3.txt"); // InputStream stream = FilePathTest.class.getClassLoader().getResourceAsStream("test2.txt"); BufferedReader reader = new BufferedReader(new InputStreamReader(stream)); String line = null; try { while((line = reader.readLine()) != null) { System.out.println(line); } } catch (IOException e) { e.printStackTrace(); } //使用类加载路径获取test2.txt File file2ByLoard = new File(FilePathTest.class.getResource("/").getPath() + "\\test2.txt"); System.out.println("test2.txt exists by load " + file2ByLoard.exists()); File file2ByLoarder = new File(FilePathTest.class.getClassLoader().getResource("").getPath() + "\\test2.txt"); System.out.println("test2.txt exists by loader " + file2ByLoarder.exists()); File file2ByClasspath = new File(System.getProperty("java.class.path") + "\\test2.txt"); System.out.println("test2.txt exists by Classpath " + file2ByClasspath.exists()); } }
标签:
原文地址:http://www.cnblogs.com/scottwang/p/4450938.html