URLに基​​づいてファイルにデータを書き込むにはどうすればよいですか?

StackOverflow https://stackoverflow.com/questions/4746050

  •  13-10-2019
  •  | 
  •  

質問

try
        {
            URL url = new URL("http://localhost:8080/Files/textfile.txt");

            URLConnection connection = url.openConnection();
            connection.setDoOutput(true);
            OutputStream outStream = connection.getOutputStream();
            ObjectOutputStream objectStream = new ObjectOutputStream(outStream);
            objectStream.writeInt(637);
            objectStream.writeObject("Hello there");
            objectStream.writeObject(new Date());
            objectStream.flush();
            objectStream.close();
        }
        catch (Exception e)
        {
            System.out.println(e.toString());
        }

i am unable to write text into the file(textfile.txt) . i dn't know wat the       problem is??  can anyone explain how to write data to a text file based on url information ...  
役に立ちましたか?

解決

ファイルにローカルに書き込む必要がある(ダウンロードした後)、FTP経由で再度アップロードする必要があります。または、それがあなたのサーバーにある場合、あなたはそれをで開く必要があります File オブジェクトしてから、それに書き込み/追加します BufferedWriter 例えば。

try {
    BufferedWriter out = new BufferedWriter(new FileWriter("outfilename"));
    out.write("aString");
    out.close();
} catch (IOException e) {
    // Handle exception
}

サーバーの視点から絶対/相対パスを使用して、ファイルを書き込むために使用する必要があります。

編集: Javaのリモートファイルアクセスの詳細を読むことができます ここ.

他のヒント

のようなものを決して使用しないでください

System.out.println(e.toString());

このようにして、スタックトレースを緩め、出力はstdoutに移動し、通常はstderrに移動します。使用する

e.printStackTrace();

代わりは。ところで、どこでも不必要に例外をキャッチすることは、より大きなプログラムで大きな問題です。

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top