【问题标题】:How can i write to a .txt file stored on an online server in Java?如何写入存储在 Java 在线服务器上的 .txt 文件?
【发布时间】:2019-08-13 07:37:18
【问题描述】:

嘿嘿。我想使用 java 将特定的字符串写入我托管在我的域上的奖励空间的 .txt 文件中。在 Awardspace 上,我编辑了权限,因此允许读写。但是现在我只知道如何从文件中读取,并且它可以工作。有什么办法可以写吗?

【问题讨论】:

    标签: java


    【解决方案1】:

    您可以使用一种简单的方法来追加到文件。只需传入文件的路径和要写入文件的数据即可。

    我通常使用 UTF-8 来确保正确输出任何特殊字符。

    public static void appendToFileUtf8(String file, String data) {
        try {
            FileOutputStream fout = new FileOutputStream(file, true);
            OutputStreamWriter outwrite = new OutputStreamWriter(fout, "UTF-8");
            outwrite.write(data);
            outwrite.close();
        } catch (IOException e) {
            throw new RuntimeException("Error writing to file: "+file+" "+e.getMessage());
        }
    }
    

    【讨论】:

    • 字符串文件是url?
    • String file 是路径。如果您已经在阅读上面提到的文件,那么您应该已经有了路径。如果没有,你可以通过File.getAbsolutePath()获取文件的路径
    • .txt 文件托管在我的域上的免费托管服务 Awardspace 上,而 java 文件在我的电脑上。我设法读取了该文件,它打印了正确的内容,但我无法写入它。我尝试了 URLConnection 和各种写作方法,没有任何效果。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-05-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-22
    • 1970-01-01
    相关资源
    最近更新 更多