/** * @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读取文件转化为字符串
最新推荐文章于 2022-12-01 12:55:47 发布