java读写txt

来源:互联网 发布:seo软文代写多少钱 编辑:程序博客网 时间:2024/06/18 15:20
package com.landsea.portal.util;


import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;


public class TxtUtils {
/**
     * 读取txt文件的内容
     * @param file 想要读取的文件对象
     * @return 返回文件内容
     */
    public static String txtFile(File file){
        StringBuilder result = new StringBuilder();
        try{
        if(file.isFile() && file.exists()){ //判断文件是否存在
        InputStreamReader read = new InputStreamReader(new FileInputStream(file),"gbk");
           BufferedReader br = new BufferedReader(read);//构造一个BufferedReader类来读取文件
           String s = null;
           while((s = br.readLine())!=null){//使用readLine方法,一次读一行
               result.append(System.lineSeparator()+"&nbsp;&nbsp;"+s+"<br>");
           }
           br.close();    
        }else{
        System.out.println("找不到指定的文件");
        result.append("");
        }
        }catch(Exception e){
        System.out.println("读取文件内容出错");
            e.printStackTrace();
        }
        return result.toString();
    }
    /**
     * 写入文件
     * 
     * @param writePath
     *            文件路径
     */
    public void write(String writePath, String writeTxt) {
        try {
            File f = new File(writePath);
            if (!f.exists()) {
                f.createNewFile();
            }
            OutputStreamWriter write = new OutputStreamWriter(new FileOutputStream(f), "UTF-8");
            BufferedWriter writer = new BufferedWriter(write);
            writer.write(writeTxt);
            writer.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    public static void main(String[] args){
//        File file = new File("D:/errlog.txt");
//        System.out.println(txtFile(file));
//     TxtUtils readWrite=new TxtUtils();
//     String writePath = "D:/errlog.txt";
//     String iptMsg = "asdjaskldjklas\r\nasdjaskldjklas\r\nasdjaskldjklas";
//     readWrite.write(writePath, iptMsg);
//        System.out.println("----结束写文件----");


    }
}
原创粉丝点击