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

java 读写文件

时间:2016-09-29 21:16:23      阅读:161      评论:0      收藏:0      [点我收藏+]

标签:

1. 读文件

import java.io.*;
import java.util.*;

public class test {
    public void test_readfile(String filePath){
        File file = new File(filePath);
        FileReader fr = null;
        BufferedReader reader = null;
        try{
            fr = new FileReader(file);
            reader = new BufferedReader(fr);
            String tmpString = "";
            while((tmpString = reader.readLine()) != null){
                System.out.println(tmpString);
            }
        }
        catch (FileNotFoundException e){
            e.printStackTrace();
        }
        catch (IOException e){
            e.printStackTrace();
        }
        finally {
            try{
                reader.close();
                fr.close();
            }
            catch (IOException e){
                e.printStackTrace();
            }
        }
    }


    public static void main(String []args){
        test case1 = new test();
        String filePath = "D:\\test.txt";
        case1.test_readfile(filePath);
    }
}

2. 逐行写文件

import java.io.*;
import java.util.*;

public class test {
    public void test_writefile(String filePath){
        File file = new File(filePath);
        FileWriter fw = null;
        BufferedWriter writer = null;
        try{
            fw = new FileWriter(file);
            writer = new BufferedWriter(fw);
            writer.write("hello");
            writer.newLine(); //换行
            writer.flush();

            writer.write("123");
            writer.newLine();
        }
        catch(FileNotFoundException e){
            e.printStackTrace();
        }
        catch (IOException e){
            e.printStackTrace();
        }
        finally {
            try{
                writer.close();
                fw.close();
            }
            catch (IOException e){
                e.printStackTrace();
            }
        }
    }


    public static void main(String []args){
        test case1 = new test();
        String filePath = "D:\\test.txt";
        case1.test_writefile(filePath);
    }
}

 

java 读写文件

标签:

原文地址:http://www.cnblogs.com/kaituorensheng/p/5920722.html

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