File.pathseperator java的奇怪行为

JmR*_*Rag 3 java

我正在开发一个Java程序,它与一个文件相关联,所以我用File.separator它来管理它.

奇怪的事实是,无论我在哪个地方调用它,它\都应该返回它,因为我在Windows上工作,除了我使用它的最后一个函数.在那里,它返回;.我会给你一段我的代码,虽然我相信它不会有多大帮助.还有什么我应该知道解决这个问题吗?

 System.out.println("File:" +source+"\n");

     String filename= f.getName().substring(f.getName().lastIndexOf(File.pathSeparator)+1,f.getName().length());//here at printing I get /
     System.out.println("Filename:" +filename+"\n");

     InputStream is = null;
     OutputStream os = null;
     try {
            is = new FileInputStream(source);
            os = new FileOutputStream(output+ File.pathSeparator + filename);//here I get ;
            byte[] buffer = new byte[1024];
            int length;
            while ((length = is.read(buffer)) > 0) {
                os.write(buffer, 0, length);
            }
        } finally {
            is.close();
            os.close();
        }
Run Code Online (Sandbox Code Playgroud)

Jon*_*eet 8

不,File.pathSeparator ;在Windows上.例如,您可能有:

PATH=c:\Utils;c:\SomethingElse
Run Code Online (Sandbox Code Playgroud)

File.pathSeparator;在Windows和:Unix上.

您正在考虑在Windows和Unix 上使用File.separator哪种方法.\/

这是一个简单的方法:

import java.io.File;

public class Test {
    public static void main(String[] args) throws Exception {
        System.out.println("File.separator is " + File.separator);
        System.out.println("File.pathSeparator is " + File.pathSeparator);
    }    
}
Run Code Online (Sandbox Code Playgroud)

(在你的第一句话中你甚至谈到File.separator- 但是你File.pathSeparator在代码中使用了.)

请注意,如果您使用File类中的方法,通常根本不需要指定分隔符 - 很难确切地说明您要实现的目标,但我怀疑如下:

File file = new File(f.getName());
File outputFile = new File(output, file.getName());
// Now use outputFile
Run Code Online (Sandbox Code Playgroud)

......会更好,更清洁.