public String Read() {
try {
URL url = new URL(urlfile);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
DataInputStream in = new DataInputStream(connection.getInputStream());
// BufferedReader in = new BufferedReader(new InputStreamReader(connection.
// getInputStream()));
//DataOutputStream out = new DataOutputStream(new FileOutputStream(fileName));
byte[] a = new byte[20000];
byte[] b = new byte[20000];
int count1 = 0;
int count2 = 0;
int total = 0;
int i = 0;
String sCurrentLine = "";
String sTotalLine = "";
if ( (count1 = in.read(a)) != -1) {
System.out.println(count1);
}
if ( (count2 = in.read(b)) != -1) {
System.out.println(count2);
}
byte[] buffer = new byte[count1 + count2];
for (i = 0; i < count1; i++) {
buffer[i] = a[i];
}
for (i = 0; i < count2; i++) {
buffer[count1 + i] = b[i];
}
sun.misc.BASE64Encoder encode = new sun.misc.BASE64Encoder();
base64str = encode.encode(buffer);
// encode.encode(in,out);
//out.close();
in.close();
//return true;
}
catch (Exception e) {
System.out.println(e.toString());
}
return base64str;
}
在实际工作中,发现以上方法不能一次取得url文件的所有内容,于是又写了以下一个方法
public String Read() {
DataInputStream in = null;
try {
URL url = new URL(urlfile);
HttpURLConnection connection = (HttpURLConnection) url.
openConnection();
in = new DataInputStream(connection.getInputStream());
}
catch (IOException eIo) {}
ByteArrayOutputStream bo = new ByteArrayOutputStream();
DataOutputStream out = new DataOutputStream(bo);
sun.misc.BASE64Encoder encoder = new sun.misc.BASE64Encoder();
try {
encoder.encode(in, out);
}
catch (IOException eIo) {}
return new String(bo.toByteArray());
}