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

Java文件IO操作实例

时间:2018-01-18 22:03:43      阅读:151      评论:0      收藏:0      [点我收藏+]

标签:文件   模式   技术分享   源代码   java   分享   src   out   tac   

本文旨在以实例的方式说明java的文件io操作的基本方法和流程。

源代码

 1 import java.io.*;
 2 
 3 public class Main {
 4     final static String FILENAME="Alice.txt";
 5     //文件名
 6     public static void main(String[] args) {
 7         int count=1;
 8         String dir=System.getProperty("user.dir");
 9         System.out.println("The default dir is "+dir);
10         //显示当前路径
11         File file=new File(dir+FILENAME);
12         try {
13             file.createNewFile();
14             //创建文件,当调用createNewFile()方法时已有同名文件,则不做更改返回false
15         }catch (IOException e)
16         {
17             e.printStackTrace();
18         }
19         if(file.exists()) System.out.println("The file is exist.");
20         if(file.canRead()) System.out.println("The file can read. Lenth: "+file.length());
21         if(file.canWrite()) System.out.println("The file can write");
22         //file.delete();
23         //file.getPath();
24         //一些file的实用方法
25         PrintWriter printWriter=null;
26         BufferedWriter bufferedWriter=null;
27         //不要在try里声明变量,变量在finally中会访问不了
28         try{
29             printWriter=new PrintWriter(new FileOutputStream(FILENAME,false));
30             //如果不存在文件,会创建新文件
31             //第二个参数:Boolean append;true时采用“添加模式”,不创建新文件,false时创建新文件
32             printWriter.println(count++ +": "+"My Name is Alice.");
33             printWriter.println(count++ +": "+"I Want to write code.");
34             printWriter.println(count++ +": "+"I want to have another dance.");
35             //写入文件
36 
37         }catch (IOException e)
38         {
39             e.printStackTrace();
40         }
41         finally {
42             if(printWriter!=null)
43             printWriter.close();
44             //关闭流
45         }
46         BufferedReader bufferedReader=null;
47         try
48         {
49             bufferedReader=new BufferedReader(new FileReader(FILENAME));
50             String what;
51             while(bufferedReader.ready())
52             {//当流中有字符,反复读出
53                 what=bufferedReader.readLine();
54                 System.out.println(what);
55             }
56             //读出文件
57         }catch (IOException e)
58         {
59             e.printStackTrace();
60         }
61         finally {
62             if(bufferedReader!=null)
63                 try {
64                     bufferedReader.close();
65                     //关闭流
66                 }catch (IOException e)
67                 {
68                     e.printStackTrace();
69                 }
70         }
71     }
72 }

 技术分享图片

Alice.txt文件↑

技术分享图片

控制台↑

Java文件IO操作实例

标签:文件   模式   技术分享   源代码   java   分享   src   out   tac   

原文地址:https://www.cnblogs.com/QEStack/p/8313044.html

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