输入输出2

编写IoDemo.java的Java应用程序,程序完成的功能是:首先读取text.txt文件内容,再通过键盘输入文件的名称为iodemo.txt,把text.txt的内容存入iodemo.txt

 1         File file = new File("d:/TextRw.txt");
 2         // 读取
 3         try {
 4             FileReader fr = new FileReader(file);
 5             char[] ch = new char[1024];
 6             String str = "";
 7             int i = 0;
 8             while ((i = fr.read(ch)) > 0) {
 9                 str += new String(ch, 0, i);
10             }
11             fr.close();
12             
13             // 控制台输入新文件名
14             Scanner sc = new Scanner(System.in);
15             System.out.println("请输入新的文件名:");
16             String str1 = sc.nextLine();
17             sc.close();
18             //文件名字修改
19             file.renameTo(new File("d:/" + str1));
20             
21             // 文件内容存入
22             FileWriter fw = new FileWriter(file);
23             fw.write(str);
24             fw.close();
25         } catch (Exception e) {
26             e.printStackTrace();
27         }

 

程序运行之前:                                                     

       

程序运行:

                

运行后:    

       

运行后的新文件内容:

 

posted @ 2016-05-31 16:48  唐枫  阅读(132)  评论(0编辑  收藏  举报