总结

相对于项目目录:new File("src/main/java/com/xcrj/file/xcrj.txt");

代码

在这里插入图片描述

package com.xcrj.file;

import java.io.*;
import java.nio.charset.Charset;

public class FilePath {
    public static void main(String[] args) {
        // 相对路径,相对于项目目录
        File file = new File("src/main/java/com/xcrj/file/xcrj.txt");
        // 绝对路径
//        File file=new File(System.getProperty("user.dir")+"/src/main/java/com/xcrj/file/xcrj.txt");
        try (
                InputStream is = new FileInputStream(file);
                BufferedInputStream bis = new BufferedInputStream(is);
        ) {
            byte[] buf = new byte[bis.available()];
            bis.read(buf);
            System.out.println(new String(buf, Charset.forName("UTF-8")));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Logo

腾讯云面向开发者汇聚海量精品云计算使用和开发经验,营造开放的云计算技术生态圈。

更多推荐