import java.net.*;
import java.io.*;
class WWW
{
public static void main(String args[])
{
byte b,bytes[];
int index = 0;
try
{
URL url = new URL("http://w33.mtci.ne.jp/~shige1/image/cube.gif");
URLConnection urlcon = url.openConnection();
urlcon.setDoInput(true);
int length = urlcon.getContentLength();
DataInputStream dis = new DataInputStream(urlcon.getInputStream());
bytes = new byte[length];
for(int i=0;i<length;i++)
{
bytes[i] = dis.readByte();
}
File file = new File(url.getFile());
FileOutputStream file_out = new FileOutputStream(file.getName());
file_out.write(bytes);
}
catch(Exception e)
{
System.out.println(e.toString());
}
}
}
Source is here. (ZIP Format,512Byte,Shift-JIS)単純に、URLクラスのインスタンスを生成しているだけです。 今回は直にGIFファイルを指定していますが、コマンドライン引数の argsを使って受け取った方が、より柔軟なプログラムと言えるでしょう。URLConnection urlcon = url.openConnection();
URLConnectionクラスを使うのに、まずは接続を確立します。 URL.openConnectionメソッドの返り値として、URLConnectionのインスタンスが返されます。urlcon.setDoInput(true);
このメソッドは、URLConnectionクラスで、入力を有効にするメソッドです。 特に設定しなくても、デフォルトはtrueなのですが、 出力を有効にする、setDoOutput(true)の呼び出しを行った場合は、 setDoInputの呼び出しが必要です。bytes = new byte[length];
今回は、扱うファイルがバイナリ(GIFファイル)なので、 byte型の配列を扱っています。 テキストを扱うなら、Stringでしょうね。File file = new File(url.getFile());
この部分は、冗長なように思うかもしれませんが、 実は、URL.getFile()が返すファイル名は、/apache_pb.gifのように、 ルートディレクトリを含んだものになっています。 しかし、このファイル名でFileOutputStreamを構築すると、正しく書き出されません。 なので、一度Fileクラスに変換して、それからFileOutputStreamを構築しています。