java io操作文件实例

java向文件中追加东西的创建文件的两种方式

1)createNewFile(); 创建

private static void bufferedWriter() {  

        FileWriter file = null;  
        BufferedWriter bw = null;  
        try {  
        File newFile=new File("e:\\test201831411.txt");
        //文件不存在,创建文件
        if(!newFile.exists()) newFile.createNewFile();
            file = new FileWriter(newFile.getAbsolutePath(),true);
            bw = new BufferedWriter(file);  
  
            //跨平台的换行符  
            bw.newLine();  
            bw.write("天行健,君子以自强不息12;");  
            bw.newLine();  
            bw.write("地势坤,君子以厚德载物。");  
            bw.newLine();  
            //缓冲区的写必须有刷新  
            bw.flush();  
        } catch (IOException e) {  
            e.printStackTrace();  
        }finally{  
            try {  
                bw.close();  
                file.close();  
            } catch (IOException e) {  
                e.printStackTrace();  
            }  
        }  
    }  

    }  


2)new FileWriter(String filepath);创建   这个方法的作用是如果文件不存在。则创建文件

猜你喜欢

转载自blog.csdn.net/hanzl1/article/details/79551957