gpt4 book ai didi

java - 在哪里提供 try catch block

转载 作者:行者123 更新时间:2023-12-02 07:22:42 24 4
gpt4 key购买 nike

我正在尝试将文件从 Windows Server1 复制到另一个 Windows Server2,但不确定将 try catch block 放在哪里。我想在复制过程正在进行时通过弹出窗口或在文本区域中显示来通知用户,当 Windows Server1 或 Windows Server2 关闭时,这是我的 swingworker 代码。提前致谢

class CopyTask extends SwingWorker<Void, Integer>
{
private File source;
private File target;
private long totalBytes = 0;
private long copiedBytes = 0;

public CopyTask(File src, File dest)
{
this.source = src;
this.target = dest;


progressAll.setValue(0);
progressCurrent.setValue(0);
}

@Override
public Void doInBackground() throws Exception
{
ta.append("Retrieving info ... ");

retrieveTotalBytes(source);
ta.append("Done!\n");

copyFiles(source, target);
return null;
}

@Override
public void process(List<Integer> chunks)
{
for(int i : chunks)
{
progressCurrent.setValue(i);
}
}

@Override
public void done()
{
setProgress(100);


}
private void retrieveTotalBytes(File sourceFile)
{
File[] files = sourceFile.listFiles();
for(File file : files)
{
if(file.isDirectory()) retrieveTotalBytes(file);
else totalBytes += file.length();
}
}

private void copyFiles(File sourceFile, File targetFile) throws IOException
{

if(sourceFile.isDirectory())
{

if(!targetFile.exists()) targetFile.mkdirs();

String[] filePaths = sourceFile.list();

for(String filePath : filePaths)
{
File srcFile = new File(sourceFile, filePath);
File destFile = new File(targetFile, filePath);

copyFiles(srcFile, destFile);
}


}
else
{

ta.append("Copying " + sourceFile.getAbsolutePath() + " to " + targetFile.getAbsolutePath() ); //appends to textarea
bis = new BufferedInputStream(new FileInputStream(sourceFile));
bos = new BufferedOutputStream(new FileOutputStream(targetFile));

long fileBytes = sourceFile.length();
long soFar = 0;

int theByte;

while((theByte = bis.read()) != -1)
{
bos.write(theByte);

setProgress((int) (copiedBytes++ * 100 / totalBytes));
publish((int) (soFar++ * 100 / fileBytes));
}



bis.close();
bos.close();
publish(100);
}
}

最佳答案

哪里是可能发生异常的行?这是我发现任何异常的第一个地方。

通常,如果您的模块很小,您可以将 try 包裹在模块中的所有实际代码中,并在最后捕获异常,特别是如果异常是致命的。然后您可以记录异常并向用户返回错误消息/状态。

但是,如果异常不是致命的,则策略会有所不同。在这种情况下,您必须在引发连接异常的地方对其进行处理,以便在连接返回时可以无缝恢复。当然,这需要更多的工作。

编辑 - 您可能希望将 bis.close()bos.close() 放在 finally block 中以确保它们关闭。这可能有些迂腐,但看起来很谨慎。

关于java - 在哪里提供 try catch block ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14011702/

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