【发布时间】:2014-08-25 13:10:29
【问题描述】:
我有一个从网页读取文件并将其写入文件的程序。大多数时候这很好用,但有时文件会损坏。我想这与网络问题有关。我该怎么做才能让我的代码更稳定?
String filename = "myfile.txt";
File file = new File(PROFilePath+"/"+filename);
//Open the connection
URL myCon = new URL("url to a page");
URLConnection uc = myCon.openConnection();
FileOutputStream outputStream = new FileOutputStream(file);
int read = 0;
byte[] bytes = new byte[1024];
while ((read = uc.getInputStream().read(bytes)) != -1) {
outputStream.write(bytes, 0, read);
}
uc.getInputStream().close();
outputStream.close();
【问题讨论】:
-
你得到什么样的异常?
-
我没有得到任何异常,但是文件“损坏”/不正确的代码页/字符。如果只是重新启动我的应用程序,它就可以工作。并且它永远不会仅在服务器上本地失败。因此我猜它与网络有关。我应该将 byte[1024] 更改为另一个值吗?我应该改用 HttpUrlConnection 吗?