java读写文本文件

来源:互联网 发布:核盾网络验证是什么 编辑:程序博客网 时间:2024/05/22 05:02

Java读写文本文件,可以是txt,html等

//读取文件 (文件路径,文件编码)
public String Read(String filepath,String coding) throws Exception{
    String templateContent = "";
     FileInputStream fileinputstream = new FileInputStream(filepath);// 读取模板文件
     int lenght = fileinputstream.available();
     byte bytes[] = new byte[lenght];
     fileinputstream.read(bytes);
     fileinputstream.close();
     //System.out.println(bytes);
     templateContent = new   String(bytes,   coding); ;
     //System.out.print(templateContent);
     return templateContent;
}
//生成(生成文件路径,写入的String,文件编码)
public void Save(String filepath,String stream,String coding) throws Exception{
    File file = new File(filepath);
            FileOutputStream fos = new FileOutputStream(file);  
            Writer out = new OutputStreamWriter(fos, coding);  
            out.write(stream);  
            out.flush();  
            out.close();  
            fos.close();  
            fos.flush();

调用如:对象.Read(path+"//test.txt","GBK"); 可以是GBK UTF-8等

原创粉丝点击