T001-UT001-0024

来源:互联网 发布:同花顺数据接口教程 编辑:程序博客网 时间:2024/06/03 11:40

文件读写练习——创建文件


编写一个程序,从标准输入设备上输入一个待创建的文件名,敲击回车后创建该文件,并接着将从终端上输入的每行字符串输入到文件中,当输入的一行为 :wq时退出程序。

举例一:

输入:

1
2
3
4
5
input a file:
d:/test.txt
Hello world!
Here is my first file!
:wq

输出:

检查d:/test.txt文件中的内容,确保其内容是:

Hello world!
Here is my first file!

 代码如下:

import java.io.BufferedReader;import java.io.BufferedWriter;import java.io.File;import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.FileWriter;import java.io.IOException;import java.io.InputStreamReader;import java.io.PrintWriter;import java.util.Scanner;public class D0024 {public static void main(String[] args) throws IOException { Scanner input=new Scanner(System.in);    String fileName = null;     System.out.println("input a file:");    fileName=input.nextLine();    File file=new File(fileName);    if(!file.exists()){//如果不存在则创建文件夹    try {    file.createNewFile();    } catch (IOException e) {    e.printStackTrace();    }    }    //循环读入到文件中    //userPrint(fileName);    userwrite(fileName);    //ToWrite(fileName);}public static void userwrite(String filepath) throws IOException{         PrintWriter out = new PrintWriter(new FileWriter(filepath,true));          Scanner input=new Scanner(System.in);        String line = input.nextLine();          while(!line.equals(":wq"))          {              out.println(line);              line = input.nextLine();          }           out.close();          input.close();  }public static void ToWrite(String filepath){ FileWriter writer=null;try{writer=new FileWriter(filepath,true);Scanner input=new Scanner(System.in);        String line = input.nextLine();          while(!line.equals(":wq"))          {          writer.write(line+"\r\n");            line = input.nextLine();          }}catch(IOException s){s.printStackTrace();}finally{try{if(writer!=null){writer.close();}}catch(IOException e){e.printStackTrace();}}}public static void userPrint(String filePath){BufferedReader br = null;BufferedWriter bw = null;try{//通过System.in返回一个InputStream对象用于构造一个InputStreamReader对象//再用来构造一个Buffered对象br = new BufferedReader(new InputStreamReader(System.in));bw = new BufferedWriter(new FileWriter(filePath,true));//有内容写入尾部 否则不写   //true表示是否追加String str = br.readLine();//接收用户输入while(!str.equals(":wq")){//如果用户输入exit则退出循环bw.write(str);//将用户输入的字符串写入文件bw.newLine();//换行 bw.flush();        //刷新缓冲区,将缓冲区的字符写入磁盘!str = br.readLine();//继续接收输入}}catch(FileNotFoundException e){System.out.println(e.getMessage());}catch(IOException e){System.out.println(e.getMessage());}finally{try {bw.close();//关闭对象前会调用bw.flush();br.close();} catch (IOException e) {e.printStackTrace();}}}}


java文件读写:点击打开链接

(全文完)

0 0
原创粉丝点击