gpt4 book ai didi

java - 使用FileReader读取文件

转载 作者:行者123 更新时间:2023-12-01 12:05:34 25 4
gpt4 key购买 nike

今天,我阅读了Java教程中的Basic I/O,发现了一些问题:

public class CopyCharacters {
public static void main(String[] args) throws IOException {
FileReader inputStream = null;
FileWriter outputStream = null;
try {
inputStream = new FileReader("/workspaces/test/a.txt");
outputStream = new FileWriter("/workspaces/test/b.txt");
int c;
while ((c = inputStream.read()) != -1) {
outputStream.write(c);
}
} finally {
if (inputStream != null) {
inputStream.close();
}
if (outputStream != null) {
outputStream.close();
}
}
}
}

但是当我运行演示时,它失败了。在控制台中:

Exception in thread "main" java.io.FileNotFoundException: /workspaces/test/b.txt (Access is denied)
at java.io.FileOutputStream.open(Native Method)
at java.io.FileOutputStream.<init>(FileOutputStream.java:221)
at java.io.FileOutputStream.<init>(FileOutputStream.java:110)
at java.io.FileWriter.<init>(FileWriter.java:63)
at Demo.CopyCharacters.main(CopyCharacters.java:13)

我怎样才能做到这一点?

最佳答案

文件可能有锁,并禁止您打开它进行写入(即您的应用程序仍处于 Debug模式下的断点,而您忘记停止它,或者您杀死了应用程序,但进程仍在内存中运行)。您可以通过执行以下操作进行检查:

        inputStream = new FileReader("/workspaces/test/a.txt");
File outFile = new File("/workspaces/test/b.txt");
if (!outFile.canWrite()) {
System.err.println("Cannot write into file: " + outFile.getAbsolutePath());
}
outputStream = new FileWriter(outFile);

您还可以将输出文件“b.txt”重命名为其他名称,它将像以前一样工作(直到您意外再次锁定它)。另一种方法是使用临时文件:

    public static void main(String[] args) throws Exception {
FileReader inputStream = null;
FileWriter outputStream = null;
try {
inputStream = new FileReader("/workspaces/test/a.txt");
File file = File.createTempFile("test", null);
outputStream = new FileWriter(file);
System.out.println(file.getAbsolutePath());
int c;
while ((c = inputStream.read()) != -1) {
outputStream.write(c);
}
} finally {
if (inputStream != null) {
inputStream.close();
}
if (outputStream != null) {
outputStream.close();
}
}

}

适合编码(和调试)。它确保之后它会被操作系统删除。

关于java - 使用FileReader读取文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27651910/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com