【问题标题】:Java: Save to a file onlineJava:在线保存到文件
【发布时间】:2015-10-30 08:43:34
【问题描述】:

目前,我有这个:

String URL = "//Somewhere in my computer";
PrintWriter list = new PrintWriter(new FileWriter(URL, true));

是否可以写入具有文档的在线站点?例如,有些网站您只需要在该文档中写入网站的 URL。是否可以从 java 程序中读取和编辑这些内容?

这就是我为 TitanPad 服务所做的:

String someText = "Here goes magical text";

    URL url = null;
    try {
        url = new URL("https://titanpad.com/3VBeN3Xo31");
    } catch (MalformedURLException e) {
        e.printStackTrace();
    }
    URLConnection connection = null;
    try {
        connection = url.openConnection();
    } catch (IOException e) {
        e.printStackTrace();
    }

    connection.setDoOutput(true);

    OutputStream outStream = null;
    try {
        outStream = connection.getOutputStream();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    try {
        outStream.write(someText.getBytes(Charset.forName("UTF-8")));
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } 
    try {
        outStream.close();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();

【问题讨论】:

  • 是的,但是您必须更改接口/协议。有几种方法可以做到这一点,例如HTTP 客户端、(S)FTP 客户端、SSH ......更多的是您想要/必须使用的协议问题。请记住,在某些情况下,您还需要在目标 (URL) 服务器上允许甚至实现读/写/身份验证功能。我觉得您需要更好地了解要使用的协议,然后详细说明您的请求。 (例如“我想使用 Apache HTTP 客户端从/向 URL 读取/写入文件)。您的问题过于笼统,可能会导致不同的解释。
  • @medveshonok117 听起来很复杂。你确定没有简单/流畅的方法吗?任何在线服务都以某种方式构建以与 java 一起使用?
  • 接受的答案是我所说的(FTP)的一个例子。所以,这听起来一点也不复杂。但这意味着服务器必须接受 FTP 连接,并且您可以这样做。

标签: java writetofile


【解决方案1】:

你可以使用 FTP-

String someText = "Here goes magical text";

URL url = new URL("ftp://user:password@somewebsite.com/filename.txt");
URLConnection connection = url.openConnection();

connection.setDoOutput(true);

OutputStream outStream = connection.getOutputStream();

outStream.write(someText.getBytes(Charset.forName("UTF-8"))); 
outStream.close();

【讨论】:

  • 我收到了 50 多个错误。我将 URL 更改为“TitanPad”在线服务。如果是这样,我将如何使其工作?
  • @Playdowin 如果您有 ftp 访问权限和用户/通行证,您能否分享“错误”消息?
  • javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target at sun.security.ssl.Alerts.getSSLException(Alerts.java:192) ...等
  • @Playdowin 也许您可以将您的服务器证书添加到您的 JVM 的受信任证书列表中。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-07-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-12-28
  • 1970-01-01
相关资源
最近更新 更多