Java基础--读写文件

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

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