In my Java swing program, I read, edit and save various text files in a local folder using Scanner and BufferedWriter. Is there an easy way I can keep my current code, but, using FTP, edit a web file rather than a local file? Thanks everyone.
Asked
Active
Viewed 3,514 times
2 Answers
1
I tried to achieve the same and the answers to those questions helped me a lot:
Adding characters to beginning and end of InputStream in Java (the one marked as right shows how to add a custom string to the InputStream)
Uploading a file to a FTP server from android phone? (the one from Kumar Vivek Mitra shows how to upload a file)
I added new text to the end of my online file like this:
FTPClient con = null;
try {
con = new FTPClient();
con.connect(Hostname);
if (con.login(FTPUsername, FTPPassword)) {
con.enterLocalPassiveMode(); // important!
con.setFileType(FTP.BINARY_FILE_TYPE);
InputStream onlineDataIS = urlOfOnlineFile.openStream();
String end = "\nteeeeeeeeeeeeeeeeest";
List<InputStream> streams = Arrays.asList(
onlineDataIS,
new ByteArrayInputStream(end.getBytes()));
InputStream resultIS = new SequenceInputStream(Collections.enumeration(streams));
// Stores a file on the server using the given name and taking input from the given InputStream.
boolean result = con.storeFile(PathOfTargetFile, resultIS);
onlineDataIS.close();
resultIS.close();
if (result) Log.v("upload result", "succeeded");
con.logout();
con.disconnect();
}
return "Writing successful";
} catch (IOException e) {
// some smart error handling
}
Hope that helps.
1
You can use the URL and URLConnection classes to obtain InputStreams and OutputStreams to files located on an FTP Server.
To read a file
URL url = new URL("ftp://user:pass@my.ftphost.com/myfile.txt");
InputStream in = url.openStream();
to write a file
URL url = new URL("ftp://user:pass@my.ftphost.com/myfile.txt");
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
OutputStream out = conn.getOutputStream();

3urdoch
- 7,192
- 8
- 42
- 58
-
`URL url=new URL("ftp://user:pass@my.ftphost.com/myfile.txt"); URLConnection connection = url.openConnection(); connection.setDoOutput(true); OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream()); out.write("Good morning Starshine! The earth says HELLOOO!!"); out.close();` This didn't work for me... – kAmol May 31 '14 at 20:12