在这段java代码中,
import java.io.IOException;
public class Copy
{
public static void main(String[] args)
{
if (args.length != 2)
{
System.err.println("usage: java Copy srcFile dstFile");
return;
}
int fileHandleSrc = 0;
int fileHandleDst = 1;
try
{
fileHandleSrc = open(args[0]);
fileHandleDst = create(args[1]);
copy(fileHandleSrc, fileHandleDst);
}
catch (IOException ioe)
{
System.err.println("I/O error: " + ioe.getMessage());
return;
}
finally
{
close(fileHandleSrc);
close(fileHandleDst);
}
}
static int open(String filename)
{
return 1; // Assume that filename is mapped to integer.
}
static int create(String filename)
{
return 2; // Assume that filename is mapped to integer.
}
static void close(int fileHandle)
{
System.out.println("closing file: " + fileHandle);
}
static void copy(int fileHandleSrc, int fileHandleDst) throws IOException
{
System.out.println("copying file " + fileHandleSrc + " to file " +
fileHandleDst);
if (Math.random() < 0.5)
throw new IOException("unable to copy file");
System.out.println("After exception");
}
}
我期望的输出是
copying file 1 to file 2
I/O error: unable to copy file
closing file: 1
closing file: 2
然而,有时我会得到这个预期的输出,而有时我会得到以下输出:
copying file 1 to file 2
closing file: 1
closing file: 2
I/O error: unable to copy file
有时甚至是这样的输出:
I/O error: unable to copy file
copying file 1 to file 2
closing file: 1
closing file: 2
无论我得到第一个、第二个还是第三个输出,似乎在每次执行过程中都是随机发生的。我发现这个帖子这显然讨论了同样的问题,但我仍然不明白为什么我有时会得到输出 1、2 或 3。如果我正确理解这段代码,那么输出 1 应该是我每次得到的(异常发生)。如何确保我始终如一地获得输出 1,或者能够判断何时获得输出 1 或者何时获得输出 1
得到输出 2 或 3?
问题是您正在将一些输出写入System.out
和一些System.err
。这些是独立的流,具有独立的缓冲。据我所知,没有具体说明何时冲洗它们。
缺点是,当写入不同的流时,您不能使用输出显示的顺序来确定调用的顺序println()
发生。请注意,输出为System.out
始终按预期顺序出现。
就执行顺序而言,主体try
首先执行。如果它抛出异常,则相应的主体catch
然后执行子句。这finally
块总是最后执行。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)