InputStream 转 String三种方式

第一种方式:java.util.Scanner

	public static String demo1(){
		String text = "" ;
		try {
			URL url = new URL("http","baike.baidu.com",80,"/link?url=wW841T-yTu4c-dPTa15dhIw3Rg3ElGfhDL6nXZ0dcdrLuhDS1V70-CK6znTIXBjChhRIVWN0wiI0yOmMGH77UmlEdcm_xII8LpT0hKBr6oi4BG-RP3kr0ieZRksMM_Qf");
			InputStream input = url.openStream();   // 打开输入流
			Scanner scan = new Scanner(input);     
			scan.useDelimiter("\n"); 				// 设置分隔符
			while(scan.hasNext()){
				text += scan.next(); 
			}
			System.out.println(text);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return text;
	}


第二种方式:java.io.BufferedReader、java.io.InputStreamReader

	public static String demo2(){
		StringBuilder stringBuilder = new StringBuilder();
		try {
			URL url = new URL("http","baike.baidu.com",80,"/link?url=wW841T-yTu4c-dPTa15dhIw3Rg3ElGfhDL6nXZ0dcdrLuhDS1V70-CK6znTIXBjChhRIVWN0wiI0yOmMGH77UmlEdcm_xII8LpT0hKBr6oi4BG-RP3kr0ieZRksMM_Qf");
			InputStream input = url.openStream();   // 打开输入流
			BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(input));
			boolean firstLine = true;
			String line = null; ;
			while((line = bufferedReader.readLine()) != null){
			    if(!firstLine){
			        stringBuilder.append(System.getProperty("line.separator"));
			    }else{
			        firstLine = false;
			    }
			    stringBuilder.append(line);
			}
			System.out.println(stringBuilder.toString());
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return stringBuilder.toString() ;
	}

第三种方式:Apache commons IOUtils.toString 法

	public static String demo3(){
		URL url = new URL("http","baike.baidu.com",80,"/link?url=wW841T-yTu4c-dPTa15dhIw3Rg3ElGfhDL6nXZ0dcdrLuhDS1V70-CK6znTIXBjChhRIVWN0wiI0yOmMGH77UmlEdcm_xII8LpT0hKBr6oi4BG-RP3kr0ieZRksMM_Qf");
		InputStream input = url.openStream();   // 打开输入流
		String text = IOUtils.toString(input);
        System.out.println(text);
	}



你可能感兴趣的:(1000.Java)