java创建文本、文件、读文件、写文件
1 package Head18; 2 3 import java.io.BufferedReader; 4 import java.io.File; 5 import java.io.FileNotFoundException; 6 import java.io.FileReader; 7 import java.io.FileWriter; 8 import java.io.IOException; 9 10 public class Mkdirs_FileRW { 11 public static void main(String [] args) { 12 String a0="D:\\abc"; 13 String a1=a0+"\\abc.txt"; 14 File file0= new File(a0); 15 File file = new File(a1); 16 file0.mkdirs(); 17 //创建文件 18 if (!file.exists()){ 19 try { 20 file.createNewFile(); 21 System.out.println("文件创建成功"); 22 } catch (IOException e) { 23 24 e.printStackTrace(); 25 } 26 }else{ 27 System.out.println("文件已经存在"); 28 29 } 30 31 //写文件 32 try { 33 FileWriter fWriter = new FileWriter(a1, true); 34 fWriter.write("测试0"+"\r\n");; 35 fWriter.flush(); 36 fWriter.close(); 37 } catch (IOException e) { 38 // TODO Auto-generated catch block 39 e.printStackTrace(); 40 } 41 42 //读文件 43 try { 44 FileReader fReader=new FileReader(file); 45 //字符流 46 BufferedReader bfReader=new BufferedReader(fReader); 47 try { 48 String bf=null; 49 while((bf=bfReader.readLine())!=null){ 50 System.out.println(bf); 51 } 52 53 } catch (IOException e) { 54 e.printStackTrace(); 55 } 56 } catch (FileNotFoundException e) { 57 e.printStackTrace(); 58 } 59 60 61 62 63 64 } 65 }