【问题标题】:Java and FTP to edit online text filesJava 和 FTP 来编辑在线文本文件
【发布时间】:2011-07-04 22:49:18
【问题描述】:

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

【问题讨论】:

    标签: java text file-upload ftp


    【解决方案1】:

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

    读取文件

    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();
    

    【讨论】:

    • 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(); 这对我不起作用...
    【解决方案2】:

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

    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
            }
    

    希望对您有所帮助。

    【讨论】:

      猜你喜欢
      • 2011-06-26
      • 2011-11-01
      • 1970-01-01
      • 1970-01-01
      • 2011-12-03
      • 2012-02-16
      • 2022-12-15
      • 1970-01-01
      • 2016-03-07
      相关资源
      最近更新 更多