开发者

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

开发者 https://www.devze.com 2023-02-06 05:44 出处:网络
try { URL url = new URL(\"http://localhost:8080/Files/textfile.txt\");开发者_StackOverflow社区 URLConnection connection = url.openConnection();
try
        {
            URL url = new URL("http://localhost:8080/Files/textfile.txt");开发者_StackOverflow社区

            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 ...  


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消