简体   繁体   English

如何根据操作系统更改文件路径

[英]how to change the file path based on the OS

i have a class which reads the list available in particular location, 我有一个类,它读取特定位置的可用列表,

the following is my code, 以下是我的代码,

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class ExceptionInFileHandling {

   @SuppressWarnings({ "rawtypes", "unchecked" })
   public static void GetDirectory(String a_Path, List a_files, List a_folders) throws IOException {
       try {
           File l_Directory = new File(a_Path);
           File[] l_files = l_Directory.listFiles();

           for (int c = 0; c < l_files.length; c++) {
               if (l_files[c].isDirectory()) {
                   a_folders.add(l_files[c].getName());
               } else {
                   a_files.add(l_files[c].getName());
               }
           }
       } catch (Exception ex){
           ex.printStackTrace();
       }

   }
   @SuppressWarnings("rawtypes")
   public static void main(String args[]) throws IOException {

       String filesLocation = "asdfasdf/sdfsdf/";
       List l_Files = new ArrayList(), l_Folders = new ArrayList();
       GetDirectory(filesLocation, l_Files, l_Folders);

       System.out.println("Files");
       System.out.println("---------------------------");
       for (Object file : l_Files) {
           System.out.println(file);
       }
       System.out.println("Done");

   }
}

in this the file path can be passed as argument and that should be taken up based on the OS, 在这个文件路径可以作为参数传递,应该根据操作系统,

filePath.replaceAll("\\\\|/", "\\" + System.getProperty("file.separator"))

is this correct? 它是否正确?

There are better ways to use file paths... 有更好的方法来使用文件路径......

// Don't do this
filePath.replaceAll("\\\\|/", "\\" + System.getProperty("file.separator"))

Use java.nio.file.path : 使用java.nio.file.path

import java.nio.file.*;

Path path = Paths.get(somePathString);
// Here is your system independent path
path.toAbsolutePath();
// Or this works too
Paths.get(somePathString).toAbsolutePath();

Use File.seperator : 使用File.seperator

// You can also input a String that has a proper file seperator like so
String filePath = "SomeDirectory" + File.separator;
// Then call your directory method
try{
    ExceptionInFileHandling.GetDirectory(filePath, ..., ...);
} catch (Exception e){}

So a simple change to your method will now work cross platform: 因此,对您的方法进行简单更改现在可以跨平台工作:

@SuppressWarnings({ "rawtypes", "unchecked" })
   public static void GetDirectory(String a_Path, List a_files, List a_folders) throws IOException {
       try {
           // File object is instead constructed 
           // with a URI by using Path.toUri()
           // Change is done here
           File l_Directory = new File(Paths.get(a_Path).toUri());

           File[] l_files = l_Directory.listFiles();
           for (int c = 0; c < l_files.length; c++) {
               if (l_files[c].isDirectory()) {
                   a_folders.add(l_files[c].getName());
               } else {
                   a_files.add(l_files[c].getName());
               }
           }
       } catch (Exception ex){
           ex.printStackTrace();
       }

   }

在调用File构造函数时,也可以在Windows上使用正斜杠作为目录分隔符。

why you are not adding java defined file separator instead of creating a string then replacing all. 为什么你不添加java定义的文件分隔符而不是创建一个字符串然后替换所有。 try it like 试试吧

String filesLocation = "asdfasdf"+File.separator+"sdfsdf"+File.separator;

The answer from you should be correct. 你的答案应该是正确的。 There is another similiar thread with answer : 还有另一个类似的线程答案:

Java regex to replace file path based on OS Java正则表达式替换基于操作系统的文件路径

Platform independent paths in Java Java中的平台无关路径

First, you should not used relative path like asdfasdf/sdfsdf/ . 首先,你不应该使用像asdfasdf/sdfsdf/这样的相对路径。 It's a big source of bugs as your path depends on your working directory. 它是一个很大的bug来源,因为你的路径取决于你的工作目录。

That thing said, your replaceAll is quite good but it can be improved like this : 那个东西说,你的replaceAll非常好,但它可以像这样改进:

filePath.replaceAll(
    "[/\\\\]+",
    Matcher.quoteReplacement(System.getProperty("file.separator")));

Using quoteReplacement is adviced in replaceAll documentation replaceAll文档中建议使用quoteReplacement

Returns a literal replacement String for the specified String. 返回指定String的文字替换String。 This method produces a String that will work as a literal replacement s in the appendReplacement method of the Matcher class. 此方法生成一个String,它将作为Matcher类的appendReplacement方法中的文字替换。 The String produced will match the sequence of characters in s treated as a literal sequence. 生成的字符串将匹配s中作为文字序列处理的字符序列。 Slashes ('\\') and dollar signs ('$') will be given no special meaning. 斜杠('\\')和美元符号('$')将没有特殊含义。

You could generate a Path object from the passed argument. 您可以从传递的参数生成Path对象。 Then you would not need to handle the file separator on your own. 然后您不需要自己处理文件分隔符。

public static void main(String[] args) {
    Path path = Paths.get(args[0]);
    System.out.println("path = " + path.toAbsolutePath());
}

The code is able to handle following passed arguments. 代码能够处理以下传递的参数。

  • foo\\bar FOO \\酒吧
  • foo/bar 富/酒吧
  • foo\\bar/baz FOO \\酒吧/巴兹
  • foo\\\\bar FOO \\\\酒吧
  • foo//baz FOO //巴兹
  • foo\\\\bar//baz FOO \\\\吧//巴兹
  • ... ...

You need to use java.io.File.separatorChar to The system-dependent default name-separator character. 您需要使用java.io.File.separatorChar来依赖于系统的默认名称分隔符。

String location = "usr"+java.io.File.separatorChar+"local"+java.io.File.separatorChar; String location =“usr”+ java.io.File.separatorChar +“local”+ java.io.File.separatorChar;

org.apache.commons.io.FilenameUtils包含许多有用的方法,例如separatorsToSystem(String path)根据您使用的操作系统转换给定路径中的分隔符。

使用以下方法了解OS文件分隔符,然后使用此方法替换所有以前的分隔符。

System.getProperty("file.separator");

Why you just dont use "/". 为什么你不使用“/”。 It is acceptable for both linux and windows as path seperator. 作为路径分离器,linux和windows都可以接受。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM