我在我的程序中有一段代码,其中我指定10000作为缓冲区的大小。现在如何检查我正在复制的文件是否小于10000,例如5000,而不是如何释放剩余的5000?
谢谢。
private void copyFile(File in, File out) {
var buffer = new byte[10000];
try {
FileInputStream dis = new FileInputStream(in);
FileOutputStream dos = new FileOutputStream(out);
int count;
do {
count = dis.read(buffer);
if (count != -1)
dos.write(buffer, 0, count);
} while (count != -1);
dis.close();
dos.close();
} catch (IOException e) {
program.print("Error copying file: " + e.toString() + "\n", null);
}
}编辑:还有,我可以优化这个更多吗?
发布于 2020-11-13 04:55:11
流应该始终关闭。如果您的方法抛出异常,您将出现资源泄漏。要么关闭finally块中的流,要么使用try-with-resources确保它们被关闭。
可选的大括号不是。在以后修改代码时,跳过大括号通常会导致错误。
用于处理流的典型循环结构看起来更像
int charsRead;
while ((charsRead = dis.read(buffer) > 0) {
// do stuff
}对于一个缓冲区来说,10,000是相当大的。这可能不是最好的选择。
请不要吞下堆栈的痕迹。当这段代码需要稍后调试时,这是关键信息。
意见:var很讨厌。
如果应用所有这些更改,您的代码可能更类似于:
private void copyFile(File in, File out) {
byte[] buffer = new byte[1024];
try (FileInputStream dis = new FileInputStream(in);
FileOutputStream dos = new FileOutputStream(out)) {
int charsRead;
while ((buffer = dis.read(buffer) > 0) {
dos.write(buffer, 0, charsRead);
}
} catch (IOException e) {
//I don't know how to use your logging library to display exception stack trace, so..
e.printStackTrace(System.err);
}
}当然,这是假设您不能使用比较直观的名称Files.copy()。那就好多了。
private void copyFile(File in, File out) {
try {
Files.copy(in.toPath(), out.toPath());
} catch (IOException e) {
e.printStackTrace(System.err);
}
}发布于 2020-11-13 14:45:03
关于异常处理的注释。
异常是指与方法的调用方通信该方法未完成其工作。
在您的情况下,工作是复制一个文件。如果在此过程中发生异常,则很可能out文件尚未成为in文件的有效副本。你必须通知你的来电者那次失败。相反,通知用户是错误的,原因有二:
因此,最好只声明可能发生的异常,并让调用堆栈上的某些实例决定如何处理该异常。您的方法应该将其失败报告给调用方,并让他处理:
private void copyFile(File in, File out) throws IOException {
var buffer = new byte[10000];
FileInputStream dis = new FileInputStream(in);
FileOutputStream dos = new FileOutputStream(out);
int count;
do {
count = dis.read(buffer);
if (count != -1)
dos.write(buffer, 0, count);
} while (count != -1);
dis.close();
dos.close();
}发布于 2020-12-02 14:08:39
很少有事情需要研究
https://www.javatpoint.com/finally-block-in-exception-handling
https://codereview.stackexchange.com/questions/252025
复制相似问题