T001-UT001-0024
来源:互联网 发布:同花顺数据接口教程 编辑:程序博客网 时间:2024/06/03 11:40
文件读写练习——创建文件
编写一个程序,从标准输入设备上输入一个待创建的文件名,敲击回车后创建该文件,并接着将从终端上输入的每行字符串输入到文件中,当输入的一行为 :wq时退出程序。
举例一:
输入:
输出:
检查d:/test.txt文件中的内容,确保其内容是:
代码如下:
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
- T001-UT001-0024
- T001-UT001-0017
- T001-UT001-0016
- T001-UT001-0018
- T001-UT001-0019
- T001-UT001-0001
- T001-UT001-0002
- T001-UT001-0003
- T001-UT001-0004
- T001-UT001-0005
- T001-UT001-0006
- T001-UT001-0007
- T001-UT001-0008
- T001-UT001-0009
- T001-UT001-0010
- T001-UT001-0011
- T001-UT001-0012
- T001-UT001-0013
- 一个 AES 加解密工具类
- 【SQL0003】group by AND count()
- uva12260(DP)
- 以Blog为例阐述Git多人协作开发流程
- 学习opencv—cvHoughLines2
- T001-UT001-0024
- 用gdisk给win7划分出3个分区
- RTP的几种封包方式
- UVA - 1149 Bin Packing 贪心水题
- 我的tmux配置
- T001-UT001-0025
- linux 如何查看某个程序的进程号
- 进销存系统帮助
- Python: binascii模块