文档详情

java实验IO流.docx

发布:2017-12-12约4.98千字共7页下载文档
文本预览下载声明
实验五 Java 输入输出流1.实验目的(1) 掌握输入输出流的总体结构;(2) 掌握流的概念;(3) 了解各种流(包括文件流、管道流、连接文件、过滤流、对象的序列化、随机访问)的使用。2.实验内容实验题1编写一个Java Application程序,打印命令行输入的所有参数。[基本要求]编写完整程序。代码:packagecn.shangji.sjIO;importjava.io.BufferedReader;importjava.io.BufferedWriter;importjava.io.File;importjava.io.FileWriter;importjava.io.IOException;importjava.io.InputStreamReader;publicclass Application1 {publicstaticvoid main(String[] args){File f1=newFile(d:\\,Application2.txt);try{if(!f1.exists())f1.createNewFile();BufferedReader in2=newBufferedReader(newInputStreamReader(System.in));System.out.println(请在此输入参数:);String str=in2.readLine();System.out.println(输入的参数是:+str);FileWriter out1=newFileWriter(f1,true);BufferedWriter out2=newBufferedWriter(out1);out2.write(str);in2.close();out2.close();}catch(IOException e){System.out.println(error:+e);}}} 运行结果:实验题2 阅读下面程序,叙述其功能 [基本要求] 写出本题程序的功能。packagecn.shangji.sjIO;importjava.io.FileReader;importjava.io.IOException;publicclassFileViewer { //该程序是用来答应一个给定路径的文件的内容的。/** Defines the entry point of the program. */publicstaticvoid main(String[] args) { //运行后,输入文件的绝对路径。System.out.println(Please enter the file path:);try {String fileName = ;while(true) {intreadByte = System.in.read(); //该语句每次只能读取一个字节,此处readByte是放回该字符的ASCII码值if(readByte == -1 || readByte == \r)//当read()找不到字符或者是遇到了‘\r’换行符的话,就跳出循环!break;fileName += (char) readByte; //通过循环依次把readByte转换成char型后,组成字符串,就是文件的路径了!}// Reads the file and prints it to the System.out stream.char[] buffer = newchar[20]; //声明一个字节数组FileReader reader = newFileReader(fileName);//使用filename创建FileReader对象while(true) {int length = reader.read(buffer); //每次读取length个字符出来if(length 0) // Reads a long as there is more data.break;String text = new String(buffer, 0, length); //转换成字符串后打印出来System.out.print(text);}} catch (IOException e) {e.printStackTrace(); //异常定位输出……由于System.in.read()只能每次读取一个字节,接收一个字符,……} //汉字在java里边是一个占两个字节的字符,所以的话,读取汉字会乱码!在该运行程序时,不能带有汉字的路径。}}实验题3 设计一个类Fi
显示全部
相似文档