Java和FTP编辑在线文本文件

时间:2011-02-26 17:25:56

标签: java text file-upload ftp

在我的Java swing程序中,我使用Scanner和BufferedWriter读取,编辑和保存本地文件夹中的各种文本文件。有没有一种简单的方法可以保留我当前的代码,但是,使用FTP编辑Web文件而不是本地文件?谢谢大家。

2 个答案:

答案 0 :(得分:1)

您可以使用URL和URLConnection类将InputStreams和OutputStreams获取到位于FTP服务器上的文件。

阅读文件

URL url = new URL("ftp://user:pass@my.ftphost.com/myfile.txt");
InputStream in = url.openStream();

写一个文件

URL url = new URL("ftp://user:pass@my.ftphost.com/myfile.txt");
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
OutputStream out = conn.getOutputStream();

答案 1 :(得分:1)

我试图达到同样的目的,这些问题的答案对我帮助很大:

Adding characters to beginning and end of InputStream in Java(标记为右边的那个显示了如何向InputStream添加自定义字符串)

Uploading a file to a FTP server from android phone?(来自Kumar Vivek Mitra的人展示了如何上传文件)

我在我的在线文件末尾添加了新文字,如下所示:

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
        }

希望有所帮助。