Question

I have text file on my ftp server. I am trying to write into this file but couldn't. This is my code.

URL  url = new URL("ftp://username:pass@thunder.cise.ufl.edu/public/foler/a.txt;type=i");
URLConnection urlc = url.openConnection();
OutputStream os = urlc.getOutputStream(); // To upload
OutputStream buffer = new BufferedOutputStream(os);
ObjectOutput output = new ObjectOutputStream(buffer);
output.writeChars("hello");
buffer.close();
os.close();
output.close();
Was it helpful?

Solution

ObjectOutputStream class is intended to write object data so it can be reconstructed by ObjectInputStream (see here). It's not for writing textual files. If all you need is writing String to stream better use PrintStream

URL  url = new URL("ftp://username:pass@thunder.cise.ufl.edu/public/foler/a.txt;type=i");
URLConnection urlc = url.openConnection();
OutputStream os = urlc.getOutputStream(); // To upload
OutputStream buffer = new BufferedOutputStream(os);
PrintStream output = new PrintStream(buffer);
output.print("hello");

buffer.close();
os.close();
output.close();

OTHER TIPS

what library do you use?

I think you must use a right java library when connecting to FTP

I used this one in my previous projects

ApacheCommons FTPClient

feel free to ask if you have problems using the above library.

Take a look at the question Uploading to FTP using Java and look at the answer by user Loša.

The only thing that Loša's answer is missing is the definition of the var BUFFER_SIZE as

final int BUFFER_SIZE = 1024; // or whatever size you think it should be

and importing libraries and basic class definition for what you're doing.

Some simple searching here, or via DuckDuckGo or Google would have found what you're looking for.

Also, you aren't asking a question so much as saying "This doesn't work and I don't know why. Fix it for me."

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top