Java指定编码格式读写文件

来源:互联网 发布:java excel预览插件 编辑:程序博客网 时间:2024/06/05 20:44

在实际开发中,会出现乱码问题,所以需要指定的编码格式去读写文件。

代码如下:读和写

//读文件     public static String ToString(File file){                String result = "";               try{                    BufferedReader br = new BufferedReader(new InputStreamReader(                              new FileInputStream(file), "utf-8"));//构造一个BufferedReader类来读取文件                    String s = null;                    while((s = br.readLine())!=null){//使用readLine方法,一次读一行                         result = result + "\n" +s;                    }                    br.close();                    }catch(Exception e){                    e.printStackTrace();               }                return result;            }     //写文件     public static void toFile(String path,String text){         FileOutputStream fos=null;         try {             fos=new FileOutputStream(path);             fos.write(text.getBytes("UTF-8"));             fos.flush();        } catch (Exception e) {            // TODO Auto-generated catch block            e.printStackTrace();        } finally{            try {                if(fos!=null){                    fos.close();                }            } catch (IOException e) {                // TODO Auto-generated catch block                e.printStackTrace();            }        }     }
0 0
原创粉丝点击