简体   繁体   中英

New Created File Can't Open in Java

My else if block will verify the result from remote service.

If the result matches, it will trigger another API call to contact the remote service again. The remote service will send back a file to my client program.

I tested all my code and it is working but I am not able to open back the new file and it's showing the file was corrupted. My client program will read the file from the remote service and write it into another file name in a different directory.

This is my source code:

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();
        }
    }
}

This is my filePath mentioned in the code D:/file/red_new.docx . This is how I get my file path: String filePath = "D:/file/"+fn+"_new."+fileType; . The fn variable is the filename from the JSON string from the first API call while the fileType is the file type from the JSON string from the second API call. I add in the _new to indicate it's a new file and using java concatenate with the fn and fileType to obtain the full path.

You're creating a new output file per line of input, so you'll only ever get the last line. And you're also losing the line terminators. Try this:

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

You're also not closing the input stream.

If these files aren't all known to be text files you should be using InputStream and OutputStream .

Please use finally block to close the open streams. If stream is not closed, you can't open it until the process holding the stream is closed or released.

eg:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM