簡體   English   中英

如何根據操作系統更改文件路徑

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

我有一個類,它讀取特定位置的可用列表,

以下是我的代碼,

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

它是否正確?

有更好的方法來使用文件路徑......

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

   }

在調用File構造函數時,也可以在Windows上使用正斜杠作為目錄分隔符。

為什么你不添加java定義的文件分隔符而不是創建一個字符串然后替換所有。 試試吧

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

你的答案應該是正確的。 還有另一個類似的線程答案:

Java正則表達式替換基於操作系統的文件路徑

Java中的平台無關路徑

首先,你不應該使用像asdfasdf/sdfsdf/這樣的相對路徑。 它是一個很大的bug來源,因為你的路徑取決於你的工作目錄。

那個東西說,你的replaceAll非常好,但它可以像這樣改進:

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

replaceAll文檔中建議使用quoteReplacement

返回指定String的文字替換String。 此方法生成一個String,它將作為Matcher類的appendReplacement方法中的文字替換。 生成的字符串將匹配s中作為文字序列處理的字符序列。 斜杠('\\')和美元符號('$')將沒有特殊含義。

您可以從傳遞的參數生成Path對象。 然后您不需要自己處理文件分隔符。

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

代碼能夠處理以下傳遞的參數。

  • FOO \\酒吧
  • 富/酒吧
  • FOO \\酒吧/巴茲
  • FOO \\\\酒吧
  • FOO //巴茲
  • FOO \\\\吧//巴茲
  • ...

您需要使用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");

為什么你不使用“/”。 作為路徑分離器,linux和windows都可以接受。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM