?.class文件内的代码所在的文件的路径默认
1 举例1:读取项目根目录下的数据。 2 private static void readRoot() throws FileNotFoundException, IOException { 3 BufferedReader br = new BufferedReader(new FileReader( 4 new File("jnb.txt"))); 5 String line = br.readLine(); 6 System.out.println(line); 7 } 8 举例2:读取和class文件同目录的资源数据。 9 private static void readClassPath() throws FileNotFoundException, 10 IOException { 11 URL url= SoreceReader.class.getResource("jnb.txt"); 12 String path = url.getPath(); 13 System.out.println(path); 14 BufferedReader br = new BufferedReader( 15 new FileReader(new File(path))); 16 String line = br.readLine(); 17 System.out.println(line); 18 }
举例3:读取在src目录的资源数据。//文件放在上几级目录下 private static void readBin() throws FileNotFoundException, IOException { URL url= SoreceReader.class.getResource("../../../jnb.txt"); String path = url.getPath(); System.out.println(path); BufferedReader br = new BufferedReader( new FileReader(new File(path))); String line = br.readLine(); System.out.println(line); } 可以直接返回一个指定资源的输入流对象。 public static void main(String[] args) throws Exception{ InputStream in = SoreceReader.class.getResourceAsStream("../../../jnb.txt"); BufferedReader br = new BufferedReader( new InputStreamReader(in)); String line = br.readLine(); System.out.println(line); } getResourceAsStream VS getResource getResourceAsStream直接返回了流对象因此无法获取资源的信息。 getResource直接返回的是资源的绝对路径,那么封装File可以快速的获取资源的信息。所有在文件下载的时候一般使用该方法。