码迷,mamicode.com
首页 > 其他好文 > 详细

读写文件

时间:2016-08-17 01:35:26      阅读:141      评论:0      收藏:0      [点我收藏+]

标签:

Java读写文件需要注意异常的处理,下面是一个例子

写文件

 1 public class WriteFile {
 2     
 3     public static void write(String file, String text){
 4         try{
 5             PrintWriter out = new PrintWriter(new File(file).getAbsoluteFile());
 6             try{
 7                 out.print(text);
 8             }finally{
 9                 out.close();
10             }
11         }catch(IOException e){
12             throw new RuntimeException(e);
13         }
14     }
15     
16 
17     public static void main(String[] args) throws IOException{
18         String file = "test.txt";
19         //print current path
20         System.out.println(new File("").getAbsolutePath());
21         
22         String context = "i am context, 1234567890!@#$%^&*()";
23         write(file, context);
24     }
25 
26 }

 

读文件

public class ReadFile {

    private static BufferedReader in;

    private static void openFile(String fname) throws Exception {
        try {
            in = new BufferedReader(new FileReader(fname));
        } catch (FileNotFoundException e) {
            // can not find file, not opened so no close
            throw e;
        } catch (Exception e) {
            try {
                // maybe opened, try to close
                in.close();
            } catch (IOException e2) {
                // close failed, rare
                // exception chain
                // throw e2;
            }
            throw e;
        } finally {
            // empty, close can not be here
        }
    }

    public static String readFromFile(String fpath) throws Exception {

        openFile(fpath);
        
        StringBuffer sbf = new StringBuffer();
        String s;
        
        try {
            while ((s = in.readLine()) != null) {
                sbf.append(s);
            }
        } catch (Exception e) {
            throw e;
        } finally {
            try {
                in.close();
            } catch (IOException e) {
                throw e;
            }
        }
        
        return sbf.toString();
    }
    
    

    public static void main(String[] args) throws Exception {
        String str = readFromFile("test.txt");
        System.out.println(str);
    }

}

 

end

 

读写文件

标签:

原文地址:http://www.cnblogs.com/luangeng/p/5778368.html

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