[英]Java: How to create & write file to maven target directory
目标:尝试创建文本文件并将其写入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错误
应用程序将部署在不同的系统上,因此路径可能会改变
我不知道如何在不检索此错误的情况下返回这种情况的目标路径
错误:
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
只是用这个
字符串pathTemp = System.getProperty(“ user.dir”); //它将给出程序运行位置的根目录
字符串字符串pathTemp = pathTemp +“ / target /” + fileName; //这里是参数的文件名
路径path = Paths.get(pathTemp);
Files.write(路径,列表,Charset.defaultCharset());
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.