zoukankan      html  css  js  c++  java
  • Java获取资源文件

    比如我们有以下目录 
    |--project 
        |--src 
            |--javaapplication 
                |--Test.java 
                |--file1.txt 
            |--file2.txt 
        |--build 
            |--javaapplication 
                |--Test.class 
                |--file3.txt 
            |--file4.txt 

    在上面的目录中,有一个src目录,这是JAVA源文件的目录,有一个build目录,这是JAVA编译后文件(.class文件等)的存放目录 
    那么,我们在Test类中应该如何分别获得 
    file1.txt file2.txt file3.txt file4.txt这四个文件呢? 

    首先讲file3.txt与file4.txt 
    file3.txt: 
    方法一:File file3 = new File(Test.class.getResource("file3.txt").getFile()); 
    方法二:File file3 = new File(Test.class.getResource("/javaapplication/file3.txt").getFile()); 
    方法三:File file3 = new File(Test.class.getClassLoader().getResource("javaapplication/file3.txt").getFile()); 

    file4.txt: 
    方法一:File file4 = new File(Test.class.getResource("/file4.txt").getFile()); 
    方法二:File file4 = new File(Test.class.getClassLoader().getResource("file4.txt").getFile()); 

    但是file1与file2文件只能写上它们的绝对路径,不能像file3与file4一样用class.getResource()这种方法获得,它们的获取方法如下 (假设整个project目录放在c:/下)
    file1.txt 
    File file1 = new File("c:/project/src/javaapplication/file1.txt"); 

    file2.txt 
    File file2 = new File("c:/project/src/file2.txt"); 

    总结一下,就是你想获得文件,你得从最终生成的.class文件为着手点,不要以.java文件的路径为出发点,因为真正使用的就是.class,不会拿个.java文件就使用。
  • 相关阅读:
    47. Permutations II
    56. Merge Intervals
    57. Insert Interval
    常见算法问题
    67. Unique Paths
    版权声明
    121. Best Time to Buy and Sell Stock
    Leetcode backtracking 合集
    转载 int和string 类型的互换
    prim算法,克鲁斯卡尔算法---最小生成树
  • 原文地址:https://www.cnblogs.com/qionglouyuyu/p/4607588.html
Copyright © 2011-2022 走看看