[英]Write text file doesnt work java
这是我的项目架构:
我想写在文件“ file.txt”上,我尝试使用BufferedWriter和PrintWriter,但它没有错误没有工作。
我的BufferedWriter代码:
ClassLoader classLoader = getClass().getClassLoader();
File file = new File(classLoader.getResource("FileTLV.txt").getFile());
try{
BufferedWriter writer = new BufferedWriter(new FileWriter(file));
writer.write("I want to write a String");
writer.close();
}catch (IOException e) {
e.printStackTrace();
}
而我的代码与PrintWriter:
ClassLoader classLoader = getClass().getClassLoader();
File file = new File(classLoader.getResource("FileTLV.txt").getFile());
try{
PrintWriter writer = new PrintWriter(new FileWriter(file));
writer.print("I want to print a String");
writer.flush();
writer.close();
}catch (IOException e) {
e.printStackTrace();
}
代码执行无任何错误。
应用程序资源是只读的。 您无法写信给他们。
如果要覆盖应用程序资源,请将内容写入新位置(例如临时文件或用户主目录下的某个位置),并编写一些代码来检查该文件,然后再使用内置文件应用程序资源。
另外,URL的getFile()方法不会将URL转换为有效的文件名。 它返回URL的路径和查询部分,所有百分号转义均保持不变,因此,如果您从目录或.jar运行,其完整路径包含URL不允许的任何字符,则结果将不可用。 该方法应避免。 (方法名称来自java.net.URL是Java 1.0中存在的类,并且在发布Java 1.0时,大多数URL实际上都引用了物理文件。)
只需使用来自java.nio的Files .write(Java 7+)
这是一个例子:
List<String> lines = Arrays.asList("line1", "line2");
Path file = Paths.get("filename.txt");
Files.write(file, lines, Charset.forName("UTF-8"));
真正的好处是:
“该方法可确保在写入所有字节后(或引发I / O错误或其他运行时异常)关闭文件。”
Files.write(filePathObj, content, StandardOpenOption.APPEND);
允许您附加到文件(看看不同的OpenOptions )
通常,Files.nio确实非常有用,也可用于阅读
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.