try {
URL conn= new URL("http://www.sina.com/");
InputStream in=conn.openStream();
int n=in.available();
byte[] buf=new byte[1024];
while((n=in.read(buf))>=0){
System.out.write(buf,0,n);
}
in.close();
} catch (Exception e) {
e.printStackTrace();
}1、如何将in中的数据写入文件呢?
2、如果网页上有中文,如何正确写入文件而不会出现乱码?
谢谢各位指点
URL conn= new URL("http://www.sina.com/");
InputStream in=conn.openStream();
int n=in.available();
byte[] buf=new byte[1024];
while((n=in.read(buf))>=0){
System.out.write(buf,0,n);
}
in.close();
} catch (Exception e) {
e.printStackTrace();
}1、如何将in中的数据写入文件呢?
2、如果网页上有中文,如何正确写入文件而不会出现乱码?
谢谢各位指点
try {
fout = new FileOutputStream("d://temp//1.html");
URL conn= new URL("http://www.sina.com/");
InputStream in=conn.openStream();
int n=in.available();
byte[] buf=new byte[1024];
while((n=in.read(buf)) >=0){
System.out.write(buf,0,n);
fout.write(buf);
}
in.close();
} catch (Exception e) {
e.printStackTrace();
} finally {
if(fout != null) {
try {
fout.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
FileOutputStream fout = null;
try {
fout = new FileOutputStream("d://temp//1.html");
URL conn= new URL("http://www.sina.com/");
InputStream in=conn.openStream();
int n=in.available();
byte[] buf=new byte[1024];
while((n=in.read(buf)) >=0){
System.out.write(buf,0,n);
fout.write(buf);
}
in.close();
} catch (Exception e) {
e.printStackTrace();
} finally {
if(fout != null) {
try {
fout.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
</body>
ERROR: JDWP Unable to get JNI 1.2 environment, jvm->GetEnv() return code = -2
JDWP exit error AGENT_ERROR_NO_JNI_ENV(183): [../../../src/share/back/util.c:820]
</html>
debug:
生成成功(总时间:1 分钟 46 秒)我在netbean中测试以上代码,最后出现报错,怎么办?
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.MalformedURLException;
import java.net.URL;public class IoTest { /**
* @param args
*/
public static void main(String[] args) {
InputStream is = null;
String str = new String();
FileWriter fw = null;
BufferedWriter bw = null;
InputStreamReader isr = null;
BufferedReader br = null;
try {
URL url = new URL("http://www.sina.com/");
is = url.openStream();
} catch (MalformedURLException e) {
e.printStackTrace();
}catch(IOException e1){
e1.printStackTrace();
}
isr = new InputStreamReader(is);
br = new BufferedReader(isr);
try {
fw = new FileWriter("D:\\test\\1.html");
bw = new BufferedWriter(fw);
while((str = br.readLine())!=null){
System.out.println(str);
bw.write(str);
bw.newLine();
bw.flush();
}
} catch (IOException e) {
e.printStackTrace();
}finally{
try {
bw.close();
fw.close();
br.close();
isr.close();
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}