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

Java 如何根据操作系统更改文件路径,java,linux,windows,file,Java,Linux,Windows,File,我有一个类可以读取特定位置的列表 下面是我的代码 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

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

下面是我的代码

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

   }
}

这是否正确?

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

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


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

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

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

那东西说,你的替补很好,但可以这样改进:

filePath.replaceAll(
    "[/\\\\]+",
    Matcher.quoteReplacement(System.getProperty("file.separator")));
文件中建议使用

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


您可以根据传递的参数生成一个
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
有更好的方法来使用文件路径。。。 使用:
使用:
因此,对方法的简单更改现在可以跨平台工作:
@SuppressWarnings({“rawtypes”,“unchecked”})
公共静态void GetDirectory(字符串a\u路径、列表a\u文件、列表a\u文件夹)引发IOException{
试一试{
//而是构造文件对象
//通过使用Path.toUri()使用URI
//这里有零钱
File l_Directory=新文件(Path.get(a_Path.toUri());
File[]l_files=l_Directory.listFiles();
对于(int c=0;c
您需要对依赖于系统的默认名称分隔符字符使用
java.io.File.separatorChar


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

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

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

System.getProperty("file.separator");

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

很抱歉,我没有真正理解您的意思,请添加一些examples@JavaQuestions您只需要不修改代码。路径
asdfasdf/sdfsdf/
将被视为当前目录内的目录
sdfsdf
目录
asdfasdf
。在任何平台上。对于Windows上的反斜杠,不应替换
/
// Don't do this
filePath.replaceAll("\\\\|/", "\\" + System.getProperty("file.separator"))
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();
// 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();
       }

   }
System.getProperty("file.separator");