JavaExp9:输入输出流与文件操作
最近比较忙,没多少时间写blog。。。
**程序设计题
1 使用文件字节输入/输出流,合并两个指定的文件。
package EXP2020.exp9;
import java.io.*;
/**
* @author JM
* @date 2020/5/6
*/
public class MainTestOne {
//定义合并函数
public static void mergeFile(InputStream file1, InputStream file2, OutputStream file3) throws IOException {
//定义字节流对象,包装为缓冲流
InputStream fi1 = new BufferedInputStream(file1);
InputStream fi2 = new BufferedInputStream(file2);
OutputStream fo = new BufferedOutputStream(file3);
//设置缓冲区
byte[] data = new byte[1024];
int len = -1;
//将file1的内容写入file3
while ((len = fi1.read(data)) != -1) {
fo.write(data, 0, len);
}
//将file2的内容写入file3
while ((len = fi2.read(data)) != -1) {
fo.write(data, 0, len);
}
fo.flush();
fi1.close();
fi2.close();
fo.close();
}
public static void main(String[] args) throws IOException {
//读写文件的路径
String path1 = "file1.txt";
String path2 = "file2.txt";
String path3 = "fileMerge.txt";
//调用合并函数,第三个路径加上true来追加内容
mergeFile(new FileInputStream(path1), new FileInputStream(path2), new FileOutputStream(path3, true));
}
}
2 将java的关键字保存在一个文本中,从键盘输入一个字符串,判断是否为java的关键字。**
package EXP2020.exp9;
import java.io.*;
import java.util.Scanner;
import java.util.StringTokenizer;
/**
* @author JM
* @date 2020/5/6
*/
public class MainTestTwo {
public static void main(String[] args) throws IOException {
Scanner sc = new Scanner(System.in);
//提示用户输入要查找的关键字
System.out.println("请输入你要查找的关键字:");
String yourKey = sc.nextLine();
//读写文件路径
String path = "javakeywords.txt";
//定义缓冲流对象
BufferedReader bufferedReader = new BufferedReader(new FileReader(path));
//设置查找的状态标志
int flag = 0;
String str = null;
while ((str = bufferedReader.readLine()) != null) {
//分析逐个单词进行判断
StringTokenizer fenxi = new StringTokenizer(str);
while (fenxi.hasMoreTokens()) {
String keyword = fenxi.nextToken();
if (yourKey.equals(keyword)) {
flag = 1;
break;
}
}
if (flag == 1) break;//找到时退出第二层遍历,提高效率
}
if (flag == 1) System.out.println("成功找到。");
else System.out.println("没有找到。");
bufferedReader.close();
}
}