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

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

以下是我的代码,

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

   }

相关文章

linux常用进程通信方式包括管道(pipe)、有名管道(FIFO)、...
Linux性能观测工具按类别可分为系统级别和进程级别,系统级别...
本文详细介绍了curl命令基础和高级用法,包括跳过https的证书...
本文包含作者工作中常用到的一些命令,用于诊断网络、磁盘占满...
linux的平均负载表示运行态和就绪态及不可中断状态(正在io)的...
CPU上下文频繁切换会导致系统性能下降,切换分为进程切换、线...