跨平台——Java的File.separator

版权声明:原创不易,转载请注明出处~ https://blog.csdn.net/qq_34266804/article/details/88098098

根据部署环境获取数据存储路径

Windows下的路径分隔符和Linux下的路径分隔符是不一样的,当直接使用绝对路径时,跨平台会暴出“No such file or diretory”的异常。

比如说要在temp目录下建立一个test.txt文件,在Windows下应该这么写:
File file1 = new File ("C:\tmp\test.txt");
在Linux下则是这样的:
File file2 = new File ("/tmp/test.txt");

如果要考虑跨平台,则最好是这么写:
File myFile = new File("C:" + File.separator + "tmp" + File.separator, "test.txt");

File类有几个类似separator的静态字段,都是与系统相关的,在编程时应尽量使用。

separatorChar

public static final char separatorChar

与系统有关的默认名称分隔符。此字段被初始化为包含系统属性 file.separator 值的第一个字符。在 UNIX 系统上,此字段的值为 '/';在 Microsoft Windows 系统上,它为 '\'。

separator

public static final String separator

与系统有关的默认名称分隔符,为了方便,它被表示为一个字符串。此字符串只包含一个字符,即 separatorChar。

pathSeparatorChar

public static final char pathSeparatorChar

与系统有关的路径分隔符。此字段被初始为包含系统属性 path.separator 值的第一个字符。此字符用于分隔以路径列表 形式给定的文件序列中的文件名。在 UNIX 系统上,此字段为 ':';在 Microsoft Windows 系统上,它为 ';'。

pathSeparator

public static final String pathSeparator

与系统有关的路径分隔符,为了方便,它被表示为一个字符串。此字符串只包含一个字符,即 pathSeparatorChar。


问题:

Image image = ImageIO.read(new File(fso)); //读取文件  这句话读取  windows 下的路径下的读片
        if(!file.exists()){
    file.setWritable(true,false);    //权限
file.mkdirs();//创建多级目录

//在创建的文件夹下创建文件
ImageIO.write((BufferedImage)image, "jpg", new File(path+"\\"+id+"\\"+files+".jpg"));
System.out.println("执行了澳门");
}


这个在我本地windows上可以实现的,但是部署在Linux系统上却不能实现:

原因:

应该是你上传图片时目录的分隔符写错了,windows系统的目录是以\来作为分隔符的,linux系统的目录则正好与windows相反,是以/作为分隔符的


把你代码中的“\\”替换成File.separator就行了。File.separator是jdk提供的自动获取当前系统分隔符的命令


实例:

// 将上面的“\”全部变为“/” \需要转义
//tomcatWebapps = tomcatWebapps.replaceAll("\\\\","/"); // tomcat中的图片路径获取过来了
tomcatWebapps = tomcatWebapps.replaceAll("\\\\", Matcher.quoteReplacement(File.separator)); // tomcat中的图片路径获取过来了

仅适用于Win系统下:

// 将上面的“\”全部变为“/” \需要转义
 tomcatWebapps = tomcatWebapps.replaceAll("\\\\","/");   // tomcat中的图片路径获取过来了

适用于Win系统和Linux系统下:使用Matcher.quoteReplacement(sep)转义。

 tomcatWebapps = tomcatWebapps.replaceAll("\\\\",Matcher.quoteReplacement(File.separator)); 

猜你喜欢

转载自blog.csdn.net/qq_34266804/article/details/88098098