Java:如何创建并将文件写入maven目标目录



目标:尝试在 maven 项目中创建文本文件并将其写入目标文件夹

方法:

public synchronized void writeToFile(List<String> list, String file) {
        String path = MyClass.class.getProtectionDomain().getCodeSource().getLocation().getPath();
        try {
            Path out = Paths.get( path + file);
            Files.write(out, list, Charset.defaultCharset());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

问题:

  • java.nio.file.InvalidPathException error

  • 应用程序将部署在不同的系统上,因此路径可能会更改

  • 我不知道如何在不检索此错误的情况下返回这种情况的目标路径

错误:

Exception in thread "main" java.nio.file.InvalidPathException: Illegal char <:> at index 2: /C:/Users/jquinn/IdeaProjects/Exercise1/Word%20Scraper%20-%20Java/target/classes/exclusions.txt
    at sun.nio.fs.WindowsPathParser.normalize(WindowsPathParser.java:182)
    at sun.nio.fs.WindowsPathParser.parse(WindowsPathParser.java:153)
    at sun.nio.fs.WindowsPathParser.parse(WindowsPathParser.java:77)
    at sun.nio.fs.WindowsPath.parse(WindowsPath.java:94)
    at sun.nio.fs.WindowsFileSystem.getPath(WindowsFileSystem.java:255)
    at java.nio.file.Paths.get(Paths.java:84)
    at FileManager.writeToFile(FileManager.java:58)
    at Driver.main(Driver.java:21)

第一个/导致字符串出现问题。如果没有它,您必须获得完整的字符串。

我已经尝试与我的班级一起实现它:

String path = Test.class.getProtectionDomain().getCodeSource().getLocation().getPath();
path = path.substring(1, path.length()) + "file.txt";
System.out.println(path);
Path out = Paths.get(path);
System.out.println(out.isAbsolute());

输出:

F:/software/workspace/file.txt
true

只需使用这个

String pathTemp=System.getProperty("user.dir"); //it will give the root directory of where your program runs
String pathTemp=pathTemp+"/target/"+fileName; //here file name from the argument
Path path=Paths.get(pathTemp);
Files.write(path,list,Charset.defaultCharset());

相关内容

  • 没有找到相关文章

最新更新