读取文本的内容和将文本写入文件中

来源:互联网 发布:php伪静态 编辑:程序博客网 时间:2024/05/22 13:57
//fileaddress为文件的地址
</pre><pre name="code" class="java">import java.io.*;public class FileInput_output {/* * 读取外部文件中的文本 * */public String read(String fileaddress){String str = "";String encoding="GBK";//定义File file = new File(fileaddress);//判断文件是否存在和文件是否是标准文件if(file.isFile()&&file.exists()){try {//定义读取文件的对象InputStreamReader read = new InputStreamReader(new FileInputStream(file),encoding);//定义读取文件BufferedReader bufr = new BufferedReader(read);//定义一个变量并初始化String text = null;try {//读取一个文本行while((text = bufr.readLine()) != null){//输出文本行 // System.out.println(text);//调用加密算法//new EncrypFile().encry(text);str += text;}} catch (IOException e1) {// TODO 自动生成的 catch 块e1.printStackTrace();}            try {            //关闭文件流read.close();} catch (IOException e) {// TODO 自动生成的 catch 块e.printStackTrace();}} catch (FileNotFoundException e) {// TODO 自动生成的 catch 块e.printStackTrace();} catch (UnsupportedEncodingException e) {// TODO 自动生成的 catch 块e.printStackTrace();}}else{    System.out.println("找不到指定的文件");}return str;}/* * 将文本写入外部文件中 * */public void write(String fileaddrs,String filetext){File file = new File(fileaddrs);if(file.exists()){try {FileWriter  fiWr = new FileWriter(file,true);//定义要写入文本的文件BufferedWriter bufWri = new BufferedWriter(fiWr);//向文件中写字符bufWri.append(filetext);//关闭输出流bufWri.close();} catch (IOException e) {// TODO 自动生成的 catch 块e.printStackTrace();}}}
}

0 0