【发布时间】:2016-12-22 13:34:47
【问题描述】:
我的else if 块将验证远程服务的结果。
如果结果匹配,它将触发另一个 API 调用以再次联系远程服务。远程服务会将文件发送回我的客户端程序。
我测试了我的所有代码并且它正在工作,但我无法打开新文件并且它显示文件已损坏。我的客户端程序将从远程服务读取文件并将其写入不同目录中的另一个文件名。
这是我的源代码:
else if (result == 1 && value.equals("problem"))
{
String Url = "http://server_name:port/anything/anything/";
String DURL = Url.concat(iD);
System.out.println("URL is : " + DURL); // the remote API URL
URL theUrl = new URL (DURL);
HttpURLConnection con1 = (HttpURLConnection) theUrl.openConnection(); //API call
con1.setRequestMethod("GET");
con1.connect();
int responseCode = con1.getResponseCode();
if(responseCode == 200)
{
try
{
InputStream is1 = con1.getInputStream();
BufferedReader read1 = new BufferedReader (new InputStreamReader(is1));
String data1 = "" ;
while ((data1 = read1.readLine()) != null)
{
PrintStream ps = new PrintStream(new FileOutputStream(filePath));
ps.print(data1);
ps.close();
}
System.out.println("The new sanitized file is ready");
}
catch(IOException e)
{
e.printStackTrace();
}
}
}
这是我在代码D:/file/red_new.docx中提到的filePath。这就是我获取文件路径的方式:String filePath = "D:/file/"+fn+"_new."+fileType;。 fn 变量是来自第一个 API 调用的 JSON 字符串的文件名,而fileType 是来自第二个 API 调用的 JSON 字符串的文件类型。我添加了_new 以表明它是一个新文件,并使用java 与fn 和fileType 连接以获得完整路径。
【问题讨论】:
-
定义“无法打开新文件”,并告诉我们什么是“显示文件已损坏”。不清楚你在问什么。这些是文本文件吗?
-
您应该在 finally 块或多个 finally 块中关闭所有打开的连接/流/读取器......这些往往有助于解决不一致问题,这样做通常是一种好习惯