how can we write data to a file based on url?

By : pmad
Source: Stackoverflow.com
Question!
try
        {
            URL url = new URL("http://localhost:8080/Files/textfile.txt");

            URLConnection connection = url.openConnection();
            connection.setDoOutput(true);
            OutputStream outStream = connection.getOutputStream();
            ObjectOutputStream objectStream = new ObjectOutputStream(outStream);
            objectStream.writeInt(637);
            objectStream.writeObject("Hello there");
            objectStream.writeObject(new Date());
            objectStream.flush();
            objectStream.close();
        }
        catch (Exception e)
        {
            System.out.println(e.toString());
        }

i am unable to write text into the file(textfile.txt) . i dn't know wat the       problem is??  can anyone explain how to write data to a text file based on url information ...  
By : pmad


Answers

Never ever use things like

System.out.println(e.toString());

This way you loose the stack trace and the output goes to stdout where it normally should go to stderr. Use

e.printStackTrace();

instead. Btw., needlessly catching exceptions everywhere is a big problem in bigger programs, google out "swallowing exceptions" to learn more.



Either you need to write to the file locally (after downloading it) and then upload it via FTP again. Or if it's located on your server, you need to open it as a File object and then write/append to it with a BufferedWriter for example.

try {
    BufferedWriter out = new BufferedWriter(new FileWriter("outfilename"));
    out.write("aString");
    out.close();
} catch (IOException e) {
    // Handle exception
}

You need to use the absolute/relative path from your server's point of view to locate the file in order to write to it!

EDIT: You can read more about remote file access in java HERE.

By : Zolomon


This video can help you solving your question :)
By: admin