实习5 输入输出流
实验目的
(1) 掌握输入输出流的总体结构; (2) 掌握流的概念; (3) 了解各种流的使用。
实验题1 阅读下面程序,叙述其功能。
import java.io.FileReader; import java.io.IOException;
public class FileViewer {
/** Defines the entry point of the program. */
public static void main(String[] args) {
System.out.println(\try {
String fileName = \while (true) {
int readByte = System.in.read(); /* 1该语句每次只能
读取一个字节*/
if (readByte == -1 || readByte == '\\r') /* 2当read找不到
字符,或者字符是\\r时跳出循环 */
break;
fileName += (char) readByte; /* 3 把readByte转
换成char型,组成字符串就是文件路径*/
}
// Reads the file and prints it to the System.out stream.
char[] buffer = new char[20]; /* 4 声明数组*/ FileReader reader = new FileReader(fileName); /* 5 用fileName
创建FileReader对象*/
while (true) {
int length = reader.read(buffer); /* 6每次读取
length个字符 */
if (length < 0) // Reads a long as there is more data.
break;
String text = new String(buffer, 0, length); /* 7转换成字符串
打印出来 */
*/ } }
}
System.out.print(text);
} catch (IOException e) { }
e.printStackTrace();
[基本要求] 运行程序,并写出本题程序关键程序(1-7)的功能。 运行结果如下:
实验题2 设计一个类FileMerge, 实现从一个文件夹(文
件夹名称为“poem”,文件夹内有两个txt文件,见压缩包内文件)中依次读取每个文件的内容,然后再写入到一个新文件中,存储该文件到“poem/李白诗集.txt”。
[提示] 使用File类的listFiles()方法可以得到目录下的文件列表。
代码如下:
package shiyan5;
import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException;
public class FileMerge {
public static void main(String[] args) throws IOException {
File file = new File(\String str = \
File[] filedir = file.listFiles();
File f0 = new File(filedir[0].getPath()); File f1 = new File(filedir[1].getPath());
File f3 = new File(file,\李白诗集.txt\f3.createNewFile();
FileReader inOne; try {
inOne = new FileReader(f0);
BufferedReader inTwo = new BufferedReader(inOne);
FileWriter outone = new FileWriter(f3);
BufferedWriter outtwo = new BufferedWriter(outone); while ((str = inTwo.readLine())!=null) { outtwo.write(str); outtwo.newLine(); }
inTwo.close(); inOne.close();
inOne = new FileReader(f1);
inTwo = new BufferedReader(inOne);
outtwo.newLine();
while ((str = inTwo.readLine())!=null) {
outtwo.write(str); outtwo.newLine(); }
outtwo.close(); outone.close();
inTwo.close(); inOne.close();
}
}
} catch (FileNotFoundException e) { // TODO 自动生成的 catch 块 e.printStackTrace(); }
运行结果:
实验题 3(选做) 写一程序统计纯文本文件
“input.txt”(可以从作业管理系统中下载)的大写字母、小写字母个数,并将所有小写字母转换为大写字母,输出到“result.txt”(使用缓冲流)。
搜索“diyifanwen.net”或“第一范文网”即可找到本站免费阅读全部范文。收藏本站方便下次阅读,第一范文网,提供最新高中教育实验5 全文阅读和word下载服务。
相关推荐: