码迷,mamicode.com
首页 > 编程语言 > 详细

java读写txt文件

时间:2016-07-04 23:25:41      阅读:208      评论:0      收藏:0      [点我收藏+]

标签:

写入:

追加内容:

public static void main(String[] args) throws Exception {
        String data = " This content will append to the end of the file\n";
        File file = new File("javaio-appendfile.txt");
        if (!file.exists()) {
            file.createNewFile();
        }
        FileWriter fileWritter = new FileWriter(file.getName(), true);
        BufferedWriter bufferWritter = new BufferedWriter(fileWritter);
        bufferWritter.write(data);
        bufferWritter.close();
        System.out.println("Done");
    }

不追加的话 写成:

FileWriter fileWritter = new FileWriter(file.getName());

 读取:

public static void ss()  throws Exception{
        String filePath = "C:\\Users\\acer\\Desktop\\111.txt";
        StringBuilder sb = new StringBuilder();  
        String re = "";
        String encoding="gbk";
        File file=new File(filePath);
        if(file.isFile() && file.exists()){ //判断文件是否存在
            InputStreamReader read = new InputStreamReader(
            new FileInputStream(file),encoding);//考虑到编码格式
            BufferedReader bufferedReader = new BufferedReader(read);
            String lineTxt = null;
            int i = 0;
            while((lineTxt = bufferedReader.readLine()) != null){
                lineTxt = lineTxt.trim();
                sb.append(lineTxt);
                i++;
            }
            re = sb.toString();
            System.out.println(re.length());
            read.close();
        }
    }

 

java读写txt文件

标签:

原文地址:http://www.cnblogs.com/lishupeng/p/5641920.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!