자원 디렉토리에서 파일 경로를 읽는 여러 가지 방법

resources이 문서 에서는 디렉터리에서 파일을 가져오는 9가지 방법을 제공합니다 . 파일 인쇄 방법은 다음과 같습니다.

/**
 * 根据文件路径读取文件内容
 *
 * @param fileInPath
 * @throws IOException
 */
public static void getFileContent(Object fileInPath) throws IOException {


    BufferedReader br = null;
    if (fileInPath == null) {


        return;
    }
    if (fileInPath instanceof String) {


        br = new BufferedReader(new FileReader(new File((String) fileInPath)));
    } else if (fileInPath instanceof InputStream) {


        br = new BufferedReader(new InputStreamReader((InputStream) fileInPath));
    }
    String line;
    while ((line = br.readLine()) != null) {


        System.out.println(line);
    }
    br.close();
}

방법 1

주요 핵심 방법은 용도 getResourcegetPath방법입니다. 여기에는 getResource("")빈 문자열이 있습니다.

public void function1(String fileName) throws IOException {


    String path = this.getClass().getClassLoader().getResource("").getPath();//注意getResource("")里面是空字符串
    System.out.println(path);
    String filePath = path + fileName;
    System.out.println(filePath);
    getFileContent(filePath);
}

방법 2

주요 핵심 방법은 방법을 통해 파일 경로를 직접 가져 오는 방법 getResourcegetPath방법 입니다 . .getResource(fileName)路径中带有中文一定要使用URLDecoder.decode解码

/**
 * 直接通过文件名getPath来获取路径
 *
 * @param fileName
 * @throws IOException
 */
public void function2(String fileName) throws IOException {


    String path = this.getClass().getClassLoader().getResource(fileName).getPath();//注意getResource("")里面是空字符串
    System.out.println(path);
    String filePath = URLDecoder.decode(path, "UTF-8");//如果路径中带有中文会被URLEncoder,因此这里需要解码
    System.out.println(filePath);
    getFileContent(filePath);
}

세 번째 방법

파일명 + getFile()을 통해 직접 파일을 가져옵니다. 파일경로라면 getFile과 getPath는 같은 의미이고, URL경로라면 getPath는 매개변수가 있는 경로이다. 다음과 같이:

url.getFile()=/word/test.docx?id=123
url.getPath()=/word/test.docx

getFile()을 사용하여 파일을 가져오는 코드는 다음과 같습니다.

/**
 * 直接通过文件名+getFile()来获取
 *
 * @param fileName
 * @throws IOException
 */
public void function3(String fileName) throws IOException {


    String path = this.getClass().getClassLoader().getResource(fileName).getFile();//注意getResource("")里面是空字符串
    System.out.println(path);
    String filePath = URLDecoder.decode(path, "UTF-8");//如果路径中带有中文会被URLEncoder,因此这里需要解码
    System.out.println(filePath);
    getFileContent(filePath);
}

방법 4(중요)

위의 방법들은 모두 getResourceAsStream파일 경로를 얻어야 하지만 SpringBoot에서는 모든 파일이 jar 패키지에 있고 실제 경로가 없으므로 다음 방법을 사용할 수 있습니다.

/**
 * 直接使用getResourceAsStream方法获取流
 * springboot项目中需要使用此种方法,因为jar包中没有一个实际的路径存放文件
 *
 * @param fileName
 * @throws IOException
 */
public void function4(String fileName) throws IOException {


    InputStream in = this.getClass().getClassLoader().getResourceAsStream(fileName);
    getFileContent(in);
}

방법 5(중요)

흐름을 구하는 방법을 주로 사용하는데 getResourceAsStream사용하지 않을 경우 리소스의 루트경로에서 직접 구할 getClassLoader수 있으며 getResourceAsStream("/test.txt")SpringBoot에 있는 모든 파일은 jar 패키지에 있다 실제 경로는 없고, 따라서 다음 방법을 사용할 수 있습니다.

/**
 * 直接使用getResourceAsStream方法获取流
 * 如果不使用getClassLoader,可以使用getResourceAsStream("/test.txt")直接从resources根路径下获取
 *
 * @param fileName
 * @throws IOException
 */
public void function5(String fileName) throws IOException {


    InputStream in = this.getClass().getResourceAsStream("/" + fileName);
    getFileContent(in);
}

방법 6(중요)

클래스를 통해 파일 스트림을 가져옵니다 ClassPathResource. SpringBoot의 모든 파일은 jar 패키지에 있으며 실제 경로가 없으므로 다음 방법을 사용할 수 있습니다.

/**
 * 通过ClassPathResource类获取,建议SpringBoot中使用
 * springboot项目中需要使用此种方法,因为jar包中没有一个实际的路径存放文件
 *
 * @param fileName
 * @throws IOException
 */
public void function6(String fileName) throws IOException {


    ClassPathResource classPathResource = new ClassPathResource(fileName);
    InputStream inputStream = classPathResource.getInputStream();
    getFileContent(inputStream);
}

일곱 번째 길

절대 경로를 통해 프로젝트 내 파일의 위치를 ​​획득합니다. 이 경로는 로컬 절대 경로일 뿐이며 서버 획득에 사용할 수 없습니다.

/**
 * 通过绝对路径获取项目中文件的位置(不能用于服务器)
 * @param fileName
 * @throws IOException
 */
public void function7(String fileName) throws IOException {


    String rootPath = System.getProperty("user.dir");//E:\WorkSpace\Personal\example
    String filePath = rootPath + "\\example01\src\\main\\resources\\"+fileName;
    getFileContent(filePath);
}

여덟 번째 길

현재 절대경로를 획득 함으로써 new File("")로컬 절대경로만 가능하며 서버 획득에 사용할 수 없습니다.

/**
 * 通过绝对路径获取项目中文件的位置(不能用于服务器)
 * @param fileName
 * @throws IOException
 */
public void function8(String fileName) throws IOException {


    //参数为空
    File directory = new File("");
    //规范路径:getCanonicalPath() 方法返回绝对路径,会把 ..\ 、.\ 这样的符号解析掉
    String rootCanonicalPath = directory.getCanonicalPath();
    //绝对路径:getAbsolutePath() 方法返回文件的绝对路径,如果构造的时候是全路径就直接返回全路径,如果构造时是相对路径,就返回当前目录的路径 + 构造 File 对象时的路径
    String rootAbsolutePath =directory.getAbsolutePath();
    System.out.println(rootCanonicalPath);
    System.out.println(rootAbsolutePath);
    String filePath = rootCanonicalPath + "\\example01\\src\\main\\resources\\"+fileName;
    getFileContent(filePath);
}

방법 9

주로 환경변수를 설정하여 파일을 환경변수에 넣고 원칙도 절대경로를 통해 얻는다.
이 예에서는 환경 변수를 설정했습니다.TEST_ROOT=E:\\WorkSpace\\Personal\\example

System.getenv("TEST_ROOT");
System.getProperty("TEST_ROOT")

환경 변수를 설정한 다음 절대 경로를 통해 파일을 가져옵니다.

/**
 * 通过绝对路径获取项目中文件的位置
 *
 * @param fileName
 * @throws IOException
 */
public void function9(String fileName) throws IOException {


    System.setProperty("TEST_ROOT","E:\\WorkSpace\\Personal\\example");
    //参数为空
    String rootPath = System.getProperty("TEST_ROOT");
    System.out.println(rootPath);
    String filePath = rootPath + "\\example01\\src\\main\\resources\\"+fileName;
    getFileContent(filePath);
}

Guess you like

Origin blog.csdn.net/qq_38623939/article/details/126339977