关于字节流与字符流

时间:2021-08-14 16:16:26

同样是 下载文件,但是字符流中却不能打开文件,而字节流却能打开,不知道为啥?

/**
	 * 用的是字符流操作,竟然打不开
	 * @param url
	 * @param fileName
	 * @param title
	 */
	public static void downloadByURLAndName(String url,String fileName,String title){
		System.out.println("downloadByURLAndName");
		try {
			URL httpUrl=new URL(url);
			HttpURLConnection con=(HttpURLConnection)httpUrl.openConnection();
			
			InputStreamReader ins=new InputStreamReader(con.getInputStream(),"utf-8");
			BufferedReader br=new BufferedReader(ins);
			
			new File("F:\\imooc/Java/"+title+"/").mkdir();
			File file=new File("F:\\imooc/Java/"+title+"/"+fileName);
			FileWriter fileWriter=new FileWriter(file);
			
			String str="";
			while((str=br.readLine())!=null){
				fileWriter.write(str);
				fileWriter.flush();
			}
			fileWriter.close();
			br.close();
			ins.close();
			
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	/**
	 * 用字节流处理,竟然可以
	 * @param url
	 * @param fileName
	 * @param title
	 */
	public static void downloadByURLAndName2(String url,String fileName,String title){
	//	System.out.println("downloadByURLAndName");
		
		long startTime;
		long bytes;
		startTime=System.currentTimeMillis();
		bytes=0;
		try {
			URL httpUrl=new URL(url);
			HttpURLConnection con=(HttpURLConnection)httpUrl.openConnection();
			
			InputStream in=con.getInputStream();
			
			new File("F:\\imooc/Java/"+title+"/").mkdir();
			File file=new File("F:\\imooc/Java/"+title+"/"+fileName);
			FileOutputStream fos=new FileOutputStream(file);
			
			byte[] b=new byte[512*1024];
			int len;
			while((len=in.read(b))!=-1){
				bytes+=len;
				fos.write(b, 0, len);
			}
			fos.close();
			in.close();
			System.out.println(fileName+"下载完成");
			long endTime=System.currentTimeMillis();
			long bp=(bytes/((endTime-startTime)));
			Main.bps.add(bp);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}