Java中解决不同环境文件路径("/"和"\")报错 File.separator 用法

博客介绍了File类中的静态变量File.separator,在Windows环境下程序打印为\\\\,在Linux下为\/\。还举例说明创建test.txt文件时,Windows和Linux写法不同,强调考虑跨平台时的写法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 File.separator是File类中的静态变量

window环境下程序打印出来是:"\"

public class FileTest {


    public static void main(String[] args) throws IOException {
        File f = new File(new FileTest().getClass().getResource("").getPath());
        System.out.println("File.separator:"+File.separator);
        String pathTest = f + File.separator + "FileTest.java";
        System.out.println(pathTest);
    }
}




控制台输出:
File.separator:\
D:\day02\target\classes\com\zte\FileTest\FileTest.java

Linux下的路径分隔符是不一样的是:"/"

例如程序中要创建个test.txt文件,在Windows下应该这么写:

File file1 = new File ("D:\filepath\test.txt");


linux下则是这样的:

File file2 = new File ("/filepath/test.txt");

考虑跨平台,我们通常写:

File testFile = new File("D:" + File.separator + "filepath" + File.separator + "test.txt");

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值