JAVA第09次实验(IO流)
JAVA第09次实验(IO流)
0.字节流与二进制文件
我的代码
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
class Student {
private int id;
private String name;
private int age;
private double grade;
public Student(){
}
public Student(int id, String name, int age, double grade) {
this.id = id;
this.setName(name);
this.setAge(age);
this.setGrade(grade);
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
if (name.length()>10){
throw new IllegalArgumentException("name's length should <=10 "+name.length());
}
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
if (age<=0){
throw new IllegalArgumentException("age should >0 "+age);
}
this.age = age;
}
public double getGrade() {
return grade;
}
public void setGrade(double grade) {
if (grade<0 || grade >100){
throw new IllegalArgumentException("grade should be in [0,100] "+grade);
}
this.grade = grade;
}
@Override
public String toString() {
return "Student [id=" + id + ", name=" + name + ", age=" + age + ", grade=" + grade + "]";
}
}
public class Main {
public static void main(String[] args)
{
String fileName="f:/student.txt";
try(DataOutputStream dos=new DataOutputStream(new FileOutputStream(fileName)))
{
Student[] stu=new Student[3];
stu[0]=new Student(1,"zhangsan",19,65.0);
stu[1]=new Student(2,"lisi",19,75.0);
stu[2]=new Student(3,"wangwu",20,85.0);
for(Student stu1:stu) {
dos.writeInt(stu1.getId());
dos.writeUTF(stu1.getName());
dos.writeInt(stu1.getAge());
dos.writeDouble(stu1.getGrade());
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.out.println("1");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.out.println("2");
}
try(DataInputStream dis=new DataInputStream(new FileInputStream(fileName)))
{
while(dis!=null) {
int id=dis.readInt();
String name=dis.readUTF();
int age=dis.readInt();
double grade=dis.readDouble();
Student stu=new Student(id,name,age,grade);
System.out.println(stu);
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.out.println("3");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.out.println("4");
}
}
}
我的总结
使用字节流读写文本文件用FileInputStream和FileOutputStream,DataOutputStream是字节流与字符流之间的桥梁。
1.字符流与文本文件:使用PrintWriter(写),BufferedReader(读)
我的代码
- (1)
public class Main {
public static void main(String[] args) throws IOException
{
String FileName="f:/Students.txt";
BufferedReader br = null;
try {
br = new BufferedReader(new InputStreamReader(new FileInputStream(FileName),"UTF-8"));
String line = null;
while((line=br.readLine())!=null)
System.out.println(line);
} finally{
if (br!=null){
br.close();
}
}
}
}
- (2)
public static void ListreadStudents(String fileName){
ArrayList<Student> StudentList=new ArrayList<Student>();
BufferedReader br = null;
try {
br = new BufferedReader(new InputStreamReader(new FileInputStream(fileName),"UTF-8"));
while(br!=null) {
String line=br.readLine();
String[] stu=line.split("\\s+");
int id=Integer.parseInt(stu[0]);
String name=stu[1];
int age=Integer.parseInt(stu[2]);
double grade=Double.parseDouble(stu[3]);
Student Stu=new Student(id,name,age,grade);
StudentList.add(Stu);
}
} finally{
if (br!=null){
br.close();
}
}
}
- (3)
String FileName="f:Students.txt";
PrintWriter pw=new PrintWriter(new OutputStreamWriter(new FileOutputStream(FileName,true),"UTF-8"));
pw.print("4 wanger 21 90");
pw.close();
- (4)
String FileName="f:\Students.dat";
try(
FileOutputStream fos=new FileOutputStream(FileName);
ObjectOutputStream oos=new ObjectOutputStream(fos))
{
Student ts=new Student(5,"asd",14,60);
oos.writeObject(ts);
}
catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try(
FileInputStream fis=new FileInputStream(FileName);
ObjectInputStream ois=new ObjectInputStream(fis))
{
Student newStudent =(Student)ois.readObject();
System.out.println(newStudent);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
我的总结
(1)直接打开会出现乱码,所以在读取前要把模式改为“UTF-8”;
(2)BufferedReader类带有缓冲区,可以优先把一批数据读到缓冲区。所以后面的读取操作,是从缓冲区内获取,避免每次都是从数据 源读取数据进行字符编码转换。
2. 缓冲流(结合使用JUint进行测试)
我的代码
- PrintWriter
String FILENAME = "test.txt";
double sum=0,aver;
PrintWriter pw=null;
try {
pw = new PrintWriter(FILENAME);
for(int i = 0;i<10000000;i++){//写入1千万行
int r=new Random().nextInt(10);
sum+=r;
pw.println(r);
//System.out.println(r);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}finally{
pw.close();
}
aver=sum/10000000;
System.out.format("%.5f", aver);
}
- JUint
public class test {
@Test
public void test() {
String FILENAME = "test.txt";
long begin = System.currentTimeMillis();
Scanner scanner=null;
try {
scanner = new Scanner(new File(FILENAME));
while(scanner.hasNextLine()){//只是读出每一行,不做任何处理
scanner.nextLine();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}finally{
scanner.close();
}
long end = System.currentTimeMillis();
System.out.println("last "+(end-begin));
System.out.println("read using Scanner done");
}
@Test
public void Bufftest() {
String FILENAME = "test.txt";
long begin = System.currentTimeMillis();
BufferedReader br = null;
try {
br = new BufferedReader(new FileReader(new File(FILENAME)));
while(br.readLine()!=null){};//只是读出,不进行任何处理
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally{
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
long end = System.currentTimeMillis();
System.out.println("last "+(end-begin));
System.out.println("read using BufferedReader done");
}
}
我的总结
在处理大量数据时,使用缓冲流BufferedReader比Scanner明显快很多。
3. 字节流之对象流
我的代码
public static void writeStudent(List<Student> stuList)
{
String fileName="f:/Students.dat";
try ( FileOutputStream fos=new FileOutputStream(fileName);
ObjectOutputStream ois=new ObjectOutputStream(fos))
{
ois.writeObject(stuList);
}
catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
public static List<Student> readStudents(String fileName)
{
List<Student> stuList=new ArrayList<>();
try ( FileInputStream fis=new FileInputStream(fileName);
ObjectInputStream ois=new ObjectInputStream(fis))
{
stuList=(List<Student>)ois.readObject();
}
catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return stuList;
}
我的总结
ObjectOutputStream、ObjectInputStream与FileInputStream、FileOuputStream放在一起使用时,可以对对象永久存储。其中ObjectOutputStream、ObjectInputStream是高级流。
JAVA第09次实验(IO流)的更多相关文章
- Java第09次实验(IO流)-实验报告
0. 字节流与二进制文件 使用DataOutputStream与FileOutputStream将Student对象写入二进制文件student.data 二进制文件与文本文件的区别 try...ca ...
- Java第09次实验(IO流)
参考资料 本次作业参考文件 正则表达式参考资料 第1次实验 0. 验证 使用FileOutputStream写字节.(二进制文件与文本文件.try...catch...finally注意事项) 使用D ...
- Java第8次实验(IO流)
参考资料 本次作业参考文件 正则表达式参考资料 第1次实验 1. 字符流与文本文件:使用 PrintWriter(写),BufferedReader(读) 参考文件:基础代码目录Student.jav ...
- Java第09次实验(流与文件)
第一次实验 0. 字节流与二进制文件 1.使用DataOutputStream与FileOutputStream将Student对象写入二进制文件student.data 二进制文件与文本文件的区别 ...
- Java输入、输入、IO流 类层次关系梳理
本文主要关注在Java编程中涉及到的IO相关的类库.方法.以及对各个层次(抽线.接口继承)的流之间的关系进行梳理 相关学习资料 http://baike.baidu.com/view/1007958. ...
- Java基础知识强化之IO流笔记71:NIO之 NIO的(New IO流)介绍
1. I/O 简介 I/O ( 输入/输出 ):指的是计算机与外部世界或者一个程序与计算机的其余部分的之间的接口.它对于任何计算机系统都非常关键,因而所有 I/O 的主体实际上是内置在操作系统中的. ...
- Java基础知识强化之IO流笔记68:Properties和IO流集合使用
1. Properties和IO流集合使用 这里的集合必须是Properties集合: public void load(Reader reader):把文件中的数据读取到集合中 public v ...
- Java基础知识强化之IO流笔记66:Properties的概述 和 使用(作为Map集合使用)
1. Properties的概述 Properties:属性集合类.是一个可以和IO流相结合使用的集合类. 该类主要用于读取以项目的配置文件(以.properties结尾的文件 和 xml文件). ...
- Java笔记(二十六)……IO流上 字节流与字符流
概述 IO流用来处理设备之间的数据传输 Java对数据的操作时通过流的方式 Java用于操作流的对象都在IO包中 流按操作的数据分为:字节流和字符流 流按流向不同分为:输入流和输出流 IO流常用基类 ...
随机推荐
- P2543 [AHOI2004]奇怪的字符串
题目描述 输入输出格式 输入格式: 输入文件中包含两个字符串X和Y.当中两字符串非0即1.序列长度均小于9999. 输出格式: X和Y的最长公共子序列长度. 输入输出样例 输入样例#1: 复制 010 ...
- 6、transformation和action1
一.transformation和action入门 1.介绍 Spark支持两种RDD操作:transformation和action.transformation操作会针对已有的RDD创建一个新的R ...
- 第90节:Java中的Linux基础
第90节:Java中的Linux基础 linux是装载虚拟机上面的: JDK依赖包: yum install glibc.i686 MYSQL依赖包: yum -y install libaio.so ...
- Windows10+Jupyter notebook+添加核
链接:https://blog.csdn.net/ZWX2445205419/article/details/80113472 1. 安装Anaconda 2. 创建虚拟环境 > con ...
- 好久木来了,一直忙于项目(加懒惰),今天讲讲vuecli3.0的使用
vue更新换代很快,马上vue都要出3.0了,这是一个巨大的变革,不过今天讲的是vuecli3.0,里面使用的vue仍然是2的,所有可以放心大胆使用. Vue CLI 是一个基于 Vue.js 进行快 ...
- c++ 将字符串转换为数字
int string2int(string x); int string2int(string x){ int a; string res=x; stringstream ss; ss << ...
- Arts打卡第7周
Algorithm.主要是为了编程训练和学习. 每周至少做一个 leetcode 的算法题(先从Easy开始,然后再Medium,最后才Hard). 进行编程训练,如果不训练你看再多的算法书,你依然不 ...
- Qt 的插件制作
首先会遇到一些插件使用的问题: 插件加载的时候出现乱码 qrc:/main.qml:20: Error: Qt.createQmlObject(): failed to create object: ...
- 8. String to Integer (atoi) ---Leetcode
Implement atoi to convert a string to an integer. 题目分析: 题目本身很简单就是将一个字符串转化成一个整数,但是由于字符串的千差万别,导致在实现的时候 ...
- thymeleaf 与shiro 整合错误
错误 @Override protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) { // ...