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 ...
Asked
Active
Viewed 1.0k times
0
-
possible duplicate of [How to download and save a file from internet using Java](http://stackoverflow.com/questions/921262/how-to-download-and-save-a-file-from-internet-using-java) – dogbane Jan 20 '11 at 10:41
-
@Satya :no errors. just executed the program without any effect – pmad Jan 20 '11 at 10:43
-
@T : how to work on it? – pmad Jan 20 '11 at 10:44
-
pmad: Accept answers to your questions. :) – Zolomon Jan 20 '11 at 10:44
2 Answers
1
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.

Zolomon
- 9,359
- 10
- 36
- 49
0
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.

maaartinus
- 44,714
- 32
- 161
- 320
-
Hello maaartinus! This should be a comment as it does not answer the question directly. Nevertheless, a great advise :) – Ranhiru Jude Cooray Jan 20 '11 at 11:51
-
Sure, but at the time of writing I wasn't yet allowed to write comments. I chose to write it, since bad exception handling/reporting is one of the most terrible beginners mistakes. Next time, I'll do it right; I'm pretty new here. – maaartinus Jan 20 '11 at 13:05