【问题标题】:how to change the file path based on the OS如何根据操作系统更改文件路径
【发布时间】:2015-01-15 10:17:19
【问题描述】:

我有一个类可以读取特定位置的可用列表,

以下是我的代码,

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");

   }
}

在这种情况下,文件路径可以作为参数传递,并且应该根据操作系统来使用,

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

这对吗?

【问题讨论】:

    标签: java linux windows file


    【解决方案1】:

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

    【讨论】:

    • 很抱歉,没有真正理解你,请补充一些例子
    • @JavaQuestions 你只需要修改你的代码。路径asdfasdf/sdfsdf/ 将被视为当前目录内的目录asdfasdf 内的目录sdfsdf。在任何平台上。在 Windows 上,您不应将 / 替换为反斜杠。
    【解决方案2】:

    你的答案应该是正确的。还有另一个类似的答案:

    Java regex to replace file path based on OS

    Platform independent paths in Java

    【讨论】:

      【解决方案3】:

      为什么你不添加 java 定义的文件分隔符而不是创建一个字符串然后全部替换。 试试吧

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

      【讨论】:

        【解决方案4】:

        首先,您不应该使用像asdfasdf/sdfsdf/ 这样的相对路径。这是一个很大的错误来源,因为您的路径取决于您的工作目录。

        也就是说,您的 replaceAll 非常好,但可以这样改进:

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

        replaceAll 文档中建议使用 quoteReplacement

        返回指定字符串的文字替换字符串。此方法生成一个字符串,该字符串将用作 Matcher 类的 appendReplacement 方法中的文字替换 s。生成的 String 将匹配 s 中的字符序列,将其视为文字序列。斜杠 ('\') 和美元符号 ('$') 没有特殊含义。

        【讨论】:

          【解决方案5】:

          您可以从传递的参数生成Path 对象。这样你就不需要自己处理文件分隔符了。

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

          代码能够处理以下传递的参数。

          • foo\bar
          • foo/bar
          • foo\bar/baz
          • foo\\bar
          • foo//baz
          • foo\\bar//baz
          • ...

          【讨论】:

            【解决方案6】:

            有更好的方法来使用文件路径...

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

            使用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();
            

            使用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){}
            

            因此,对您的方法进行简单更改现在可以跨平台工作:

            @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();
                   }
            
               }
            

            【讨论】:

              【解决方案7】:

              您需要使用java.io.File.separatorChar 来与系统相关的默认名称分隔符。

              字符串位置 = "usr"+java.io.File.separatorChar+"local"+java.io.File.separatorChar;

              【讨论】:

                【解决方案8】:

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

                【讨论】:

                  【解决方案9】:

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

                  System.getProperty("file.separator");
                  

                  【讨论】:

                    【解决方案10】:

                    为什么你不使用“/”。 linux 和 windows 都可以作为路径分隔符。

                    【讨论】:

                      猜你喜欢
                      • 1970-01-01
                      • 1970-01-01
                      • 2023-03-27
                      • 2023-02-20
                      • 1970-01-01
                      • 1970-01-01
                      • 2014-12-11
                      • 1970-01-01
                      • 2015-07-16
                      相关资源
                      最近更新 更多