Paths.get(args [0])不起作用

时间:2013-04-23 10:00:47

标签: java path arguments

如何在args [0]中提供源文件,在args [1]中提供目标?我在同一个包中创建了一个source.txt和一个target.txt,并在运行配置中将“./source.txt”和“./target.txt”作为参数。但它抛出了“./ source.txt”不可读的例外。

 Exception in thread "main" java.lang.IllegalArgumnetException: ./source.txt

什么是狼?

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import de.sb.javase.TypeMetadata;


/**
   * Demonstrates copying a file using a single thread.
*/
public final class FileCopyLinear {

/**
 * Copies a file. The first argument is expected to be a qualified source file name,
 * the second a qualified target file name. 
 * @param args the VM arguments
 * @throws IOException if there's an I/O related problem
 */
public static void main(final String[] args) throws IOException {
    final Path sourcePath = Paths.get(args[0]);
    if (!Files.isReadable(sourcePath)) throw new IllegalArgumentException(sourcePath.toString());

    final Path sinkPath = Paths.get(args[1]);
    if (sinkPath.getParent() != null && !Files.isDirectory(sinkPath.getParent())) throw new IllegalArgumentException(sinkPath.toString());

    Files.copy(sourcePath, sinkPath, StandardCopyOption.REPLACE_EXISTING);

    System.out.println("done.");
}
}

2 个答案:

答案 0 :(得分:4)

相对文件路径与任何类的包无关。它们与当前目录相关,当前目录是执行java命令以启动程序的目录。

因此,如果您在目录/home/user1477955中并输入

/home/user1477955 > java com.foo.bar.FileCopyLinear source.txt target.txt

它将搜索文件/home/user1477955/source.txt/home/user1477955/target.txt

答案 1 :(得分:0)

你可以试试这个:

try {
        File file = new File(args[0]);
        BufferedReader in = new BufferedReader(new FileReader(file));
        //rest of your code
        in.close();
    } catch (IOException e) {
        System.out.println("File Read Error: " + e.getMessage());
    }