/** * @Author zhaihuali * @Description //TODO 使用FileReader讀取 * @Date 15:52 2019/10/16 0016 * @Param [url] * @return java.lang.String **/ public static String readString1(String url) { StringBuffer str=new StringBuffer(""); //File file=new File(); try { FileReader fr=new FileReader(url); int ch = 0; while((ch = fr.read())!=-1 ) { System.out.print((char)ch+""); str.append((char)ch); } fr.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); System.out.println("File reader出錯"); } return str.toString(); } /** * @Author zhaihuali * @Description //TODO 按字節讀取字符串 一次性全部讀取完後進行轉碼 * @Date 15:53 2019/10/16 0016 * @Param [url] * @return java.lang.String **/ public static String readString2(String url) { String str=""; File file = new File(url); try { FileInputStream in=new FileInputStream(file); // size 爲字串的長度 ,這裏一次性讀完 int size=in.available(); byte[] buffer=new byte[size]; in.read(buffer); in.close(); str=new String(buffer,"UTF-8"); } catch (IOException e) { e.printStackTrace(); } return str; } /** * @Author zhaihuali * @Description //TODO 按行讀對於要處理的格式化數據是一種讀取的好方式 * @Date 16:02 2019/10/16 0016 * @Param [path] * @return java.lang.String **/ public static String readString3(String path) { int len=0; StringBuffer str=new StringBuffer(""); File file=new File(path); try { FileInputStream is=new FileInputStream(file); InputStreamReader isr= new InputStreamReader(is); BufferedReader in= new BufferedReader(isr); String line=null; while( (line=in.readLine())!=null ) { if(len != 0) // 處理換行符的問題 { str.append("\r\n"+line); } else { str.append(line); } len++; } in.close(); is.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return str.toString(); }
io讀取文件轉化爲字符串
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.