【问题标题】:New Created File Can't Open in Java新创建的文件无法在 Java 中打开
【发布时间】: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 与fnfileType 连接以获得完整路径。

【问题讨论】:

  • 定义“无法打开新文件”,并告诉我们什么是“显示文件已损坏”。不清楚你在问什么。这些是文本文件吗?
  • 您应该在 finally 块或多个 finally 块中关闭所有打开的连接/流/读取器......这些往往有助于解决不一致问题,这样做通常是一种好习惯

标签: java json


【解决方案1】:

您正在为每行输入创建一个新的输出文件,因此您只会得到最后一行。而且你也失去了线路终结者。试试这个:

PrintStream ps = new PrintStream(new FileOutputStream(filePath));
while ((data1 = read1.readLine()) != null)
{
    ps.println(data1);
}
ps.close();

你也没有关闭输入流。

如果这些文件并非都是文本文件,您应该使用InputStreamOutputStream

【讨论】:

    【解决方案2】:

    请使用 finally 块关闭打开的流。如果流没有关闭,则在持有流的进程关闭或释放之前,您无法打开它。

    例如:

    try( InputStream is1 = con1.getInputStream()){
        // ...
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-11-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多