簡體   English   中英

新創建的文件無法在Java中打開

[英]New Created File Can't Open in Java

我的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以獲取完整路徑。

您將在每行輸入中創建一個新的輸出文件,因此您只會得到最后一行。 而且您還會丟失行終止符。 嘗試這個:

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

您也沒有關閉輸入流。

如果不是所有這些文件都是文本文件,則應使用InputStreamOutputStream

請使用finally塊關閉打開的流。 如果未關閉流,則在關閉或釋放保存該流的進程之前,無法打開它。

例如:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM