实验题目
一、实验目的
1、对流的基本概念的掌握。
2、对字节流和字符流的区别。
3、文件的访问与操作。
二、实验环境
1、硬件环境:个人 PC 机
2、软件环境:windows 操作系统+JDK1.8 或以上+Eclipse 或 Idea
三、实验内容
1、 编写一个程序 Digital.java,随机生成 10 个数,取值范围为 0~50。要求将生成的 10 个数从小到大写入 n.txt 文件保存。
2、 编写一个程序 HandInput.java,接受用户的键盘输入,存入指定的文件。用户的输 入以行为单位,当用户输入 end 时,程序结束。如果指定的文件已经存在,程 序提示用户,并结束程序。
四、注意事项
1、熟悉各种流的使用。
2、掌握各种流类的使用的区别。
实验内容
1. Digital类
package Test06;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
public class Digital {
public static void main(String[] args) {
Random random = new Random();
List list = new ArrayList<Integer>();
int number = 0;
for (int i = 0; i < 10 ; i++) {
number = random.nextInt(51);
if(!list.contains(number)) {
list.add(number);
}
}
try {
File write = new File(".\\n.txt");
write.createNewFile();
System.out.println("文件创建成功");
BufferedWriter out = new BufferedWriter(new FileWriter(write));
out.write(list+"\t");
System.out.println("文件写入成功");
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
2.HandInput类
package Test06;
import java.io.*;
import java.util.Scanner;
public class HandInput {
public static void main(String[] args) throws IOException {
String fileName = ".\\e.txt";// 要写入的文件路径
File file = new File(fileName);// 创建文件对象
writefile(file);
}
// 向文件中写入
public static void writefile(File file) throws IOException {
// 判断是否有该文件路径
if (file.getParentFile().exists()) {
// 判断是否有这个文件,如果没有就创建它
if (!file.exists()) {
file.createNewFile();
}
// 创建键盘录入对象
Scanner sc = new Scanner(System.in);
// 获得键盘录入字符并判断
String s = sc.nextLine();
while (!s.endsWith("end")) {
// 创建输出字节流
FileOutputStream fos = new FileOutputStream(file, true);
// 将输出字节流转化为字符流
OutputStreamWriter osw = new OutputStreamWriter(fos);
// 将字符流转化为缓存模式
BufferedWriter bw = new BufferedWriter(osw);
// 写入
bw.write(s+"\n");
// 关闭输出流
bw.close();
osw.close();
fos.close();
// 再次接受键盘录入
s = sc.nextLine();
}
}else{
System.out.println("你指定的文件路径不存在,请重新检查文件路径");
}
}
}
实验总结
1.流的概念
- 内存与存储设备之间传输数据的通道
- 数据借助流传输
2.IO的分类
按照 流的方向
以内存作为参照物:
- 往内存中去:叫做输入(Input)。或者叫做读(Read)。
- 从内存中出来:叫做输出(Output)。或者叫做写(Write)。
按照 读取数据方式
- 按照
字节
这种流是万能的,什么类型的文件都可以读取。包括:文本文件,图片,声音文件,视频文件
I: Input
O:OutPut
通过IO即可完成对磁盘的读写