0. 字节流与二进制文件

我的代码

package javalearn;

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 = "d:\\student.data"; /* 将Student对象写入二进制文件student.data */
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");
} /* 从student.data中读取学生信息并组装成对象 */
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");
} }
}

我的总结

- 1.二进制文件与文本文件的区别:二进制文件可以储存基本数据类型的变量;文本文件只能储存基本数据类型中的char类型变量。
- 2.如何优雅的关掉文件:
可以直接在try后面加一个括号,在括号中定义最后要关闭的资源。这样,不需要在catch后面加上finally,程序运行结束之后资源会自动关闭。

1. 字符流与文本文件

我的代码

  • 使用BufferedReader从编码为UTF-8的文本文件中读出学生信息,并组装成对象然后输出。
package test;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List; public class Main {
public static void main(String[] args) {
String fileName="d:/Students.txt";
List<Student> studentList = new ArrayList<>();
try(
FileInputStream fis=new FileInputStream(fileName);
InputStreamReader isr=new InputStreamReader(fis, "UTF-8");
BufferedReader br=new BufferedReader(isr))
{
String line=null;
while((line=br.readLine())!=null)
{
String[] msg=line.split("\\s+");
int id=Integer.parseInt(msg[0]);
String name=msg[1];
int age=Integer.parseInt(msg[2]);
double grade=Double.parseDouble(msg[3]);
Student stu=new Student(id,name,age,grade);
studentList.add(stu);
}
}
catch (FileNotFoundException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(studentList); }
}
  • 编写public static ListreadStudents(String fileName);从fileName指定的文本文件中读取所有学生,并将其放入到一个List中
public static List<Student> readStudents(String fileName)
{
List<Student> stuList = new ArrayList<>();
try(
FileInputStream fis=new FileInputStream(fileName);
InputStreamReader isr=new InputStreamReader(fis, "UTF-8");
BufferedReader br=new BufferedReader(isr))
{
String line=null;
while((line=br.readLine())!=null)
{
String[] msg=line.split("\\s+");
int id=Integer.parseInt(msg[0]);
String name=msg[1];
int age=Integer.parseInt(msg[2]);
double grade=Double.parseDouble(msg[3]);
Student stu=new Student(id,name,age,grade);
stuList.add(stu);
}
}
catch (FileNotFoundException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
return stuList;
}
  • 使用PrintWriter将Student对象写入文本文件
package test;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter; public class WriteFile { public static void main(String[] args) {
// TODO Auto-generated method stub
String fileName = "d:/Students.txt";
try (FileOutputStream fos = new FileOutputStream(fileName, true);
OutputStreamWriter osw = new OutputStreamWriter(fos, "UTF-8");
PrintWriter pw = new PrintWriter(osw)) {
pw.println("1 zhang 18 85");
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} }
  • 使用ObjectInputStream/ObjectOutputStream读写学生对象。
package test;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream; public class WriteFile { public static void main(String[] args) {
// TODO Auto-generated method stub
String fileName="d:/Students.dat";
try(
FileOutputStream fos=new FileOutputStream(fileName);
ObjectOutputStream oos=new ObjectOutputStream(fos))
{
Student ts=new Student(1,"lily",64,90);
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();
}
} }

2. 缓冲流(结合使用JUint进行测试)

我的代码

main函数:
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Random;
import javax.swing.text.AbstractDocument.BranchElement; public class WriteFile { public static void main(String[] args) {
// TODO Auto-generated method stub
String fileName = "e:/bigdata.txt";
int n = 1000_0000;
Random r = new Random(100); //把种子放在外面
try (PrintWriter pWriter = new PrintWriter(fileName)){ //省去finally
for (int i = 0; i < n; i++) {
pWriter.println(r.nextInt(11)); //产生0~10的随机数
}
} catch (FileNotFoundException e) {
// TODO: handle exception
e.printStackTrace();
} /*try (BufferedReader br = new BufferedReader(new FileReader(new File(fileName)))){
String string = null;
int count=0;
long sum=0;
double average = 0.0;
while ((string=br.readLine())!=null) {
int num = Integer.parseInt(string);
sum+=num;
count++;
}
average=1.0*sum/count;
System.out.format("count = %d,sum = %d,averge = %.5f",count,sum,average);
} catch (FileNotFoundException e) {
// TODO: handle exception
e.printStackTrace();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}*/
} } Junit:
package test; import static org.junit.jupiter.api.Assertions.*; import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.Scanner; import org.junit.jupiter.api.Test; class testRead {
String fileName = "e:/bigdata.txt";
@Test
void testB() {
try (BufferedReader br = new BufferedReader(new FileReader(new File(fileName)))){
String string = null;
int count=0;
long sum=0;
double average = 0.0;
while ((string=br.readLine())!=null) {
int num = Integer.parseInt(string);
sum+=num;
count++;
}
average=1.0*sum/count;
System.out.format("count = %d,sum = %d,averge = %.5f",count,sum,average);
} catch (FileNotFoundException e) {
// TODO: handle exception
e.printStackTrace();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
@Test
void testS() {
try (Scanner sc = new Scanner(new File(fileName))){
String string = null;
int count=0;
long sum=0;
double average = 0.0;
while (sc.hasNextLine()) {
string = sc.nextLine();
int num = Integer.parseInt(string);
sum+=num;
count++;
}
average=1.0*sum/count;
System.out.format("count = %d,sum = %d,averge = %.5f",count,sum,average);
} catch (FileNotFoundException e) {
// TODO: handle exception
e.printStackTrace();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
}

我的总结

- 1.在产生随机数[0.10]时。先写成了r.nextInt(10),这样只能生成[0,9]的随机数,应改为r.nextInt(11).
- 2.随机数种子应放在循环之外。
- 3.使用BufferedReader与使用Scanner从该文件中读取数据,明显使用Scanner读取文件慢的非常多。
- 4.注意格式化输出应用:System.out.format

3.字节流之对象流

我的代码

 public static void writeStudent(List<Student> stuList)
{
String fileName="D:\\Student.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;
}

5.文件操作

我的代码

public class Main {
public static void main(String[] args) {
if (args.length == 0)
args = new String[] { ".." };
try {
File pathName = new File(args[0]);
String[] fileNames = pathName.list(); // enumerate all files in the directory
for (int i = 0; i < fileNames.length; i++) {
File f = new File(pathName.getPath(), fileNames[i]); // if the file is again a directory, call the main method recursively
if (f.isDirectory()) {
if (f.getName().contains(fileName)) {
System.out.println(f.getCanonicalPath());
main(new String[] { f.getPath() });
}
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
}

我的总结

用了参考代码稍加修改,若文件名字包含fileName,则输出该文件的路径

Java——流、文件与正则表达式的更多相关文章

  1. java 流 文件 IO

    Java 流(Stream).文件(File)和IO Java.io 包几乎包含了所有操作输入.输出需要的类.所有这些流类代表了输入源和输出目标. Java.io 包中的流支持很多种格式,比如:基本类 ...

  2. Java流和文件

    File类:java.io包下与平台无关的文件和目录 java可以使用文件路径字符串来创建File实例,文件路径可以是绝对路径,也可以是相对路径,默认情况下,相对路径是依据用户工作路径,通常就是运行J ...

  3. Java 流(Stream)、文件(File)和IO

    Java.io包几乎包含了所有操作输入.输出需要的类.所有这些流类代表了输入源和输出目标. Java.io包中的流支持很多种格式,比如:基本类型.对象.本地化字符集等等. 一个流可以理解为一个数据的序 ...

  4. Java IO 文件与流基础

    Java IO 文件与流基础 @author ixenos 摘要:创建文件.文件过滤.流分类.流结构.常见流.文件流.字节数组流(缓冲区) 如何创建一个文件 #当我们调用File类的构造器时,仅仅是在 ...

  5. java IO文件操作简单基础入门例子,IO流其实没那么难

    IO是JAVASE中非常重要的一块,是面向对象的完美体现,深入学习IO,你将可以领略到很多面向对象的思想.今天整理了一份适合初学者学习的简单例子,让大家可以更深刻的理解IO流的具体操作. 1.文件拷贝 ...

  6. java 中 “文件” 和 “流” 的简单分析

    java 中 FIle 和 流的简单分析 File类 简单File 常用方法 创建一个File 对象,检验文件是否存在,若不存在就创建,然后对File的类的这部分操作进行演示,如文件的名称.大小等 / ...

  7. Java笔记:Java 流(Stream)、文件(File)和IO

    更新时间:2018-1-7 12:27:21 更多请查看在线文集:http://android.52fhy.com/java/index.html java.io 包几乎包含了所有操作输入.输出需要的 ...

  8. Java 字符流文件读写

    上篇文章,我们介绍了 Java 的文件字节流框架中的相关内容,而我们本篇文章将着重于文件字符流的相关内容. 首先需要明确一点的是,字节流处理文件的时候是基于字节的,而字符流处理文件则是基于一个个字符为 ...

  9. Java - 17 Java 流(Stream)、文件(File)和IO

    Java 流(Stream).文件(File)和IO Java.io包几乎包含了所有操作输入.输出需要的类.所有这些流类代表了输入源和输出目标. Java.io包中的流支持很多种格式,比如:基本类型. ...

  10. Java总结:Java 流(Stream)、文件(File)和IO

    更新时间:2018-1-7 12:27:21 更多请查看在线文集:http://android.52fhy.com/java/index.html java.io 包几乎包含了所有操作输入.输出需要的 ...

随机推荐

  1. Jquery table相关--工时系统

    1.jquery 的弹出对话框,单击事件之后 if (confirm("确定要删除?")) { // //点击确定后操作 } 2.对某个table中的checkbox是否被选中的遍 ...

  2. 预约系统(四) 管理页面框架搭建easyUI

    Manage控制器用于管理页面 Index视图为管理页面首页,采用easyUi的后台管理框架 Html头部调用,jquery库,easyui库,easyui.css,icon.css,语言包 < ...

  3. C#控制台输入/输出语句

    Console.Read()方法:          从控制台窗口读取一个字符,返回int值 Console.ReadLine()方法:    从控制台窗口读取一行文本,返回string值 Conso ...

  4. spring boot配置定时任务设置

    一.定时任务的时间写法: 每天凌晨2点  0 0 2 * * ?和每天隔一小时 0 * */1 * * ? 每隔5秒执行一次:*/5 * * * * ? 每隔5分执行一次:0 */5 * * * ? ...

  5. Arduino控制LED灯(开关控制)

    问题:当使用"digitalRead(BUT) == 1"控制LED灯时会出现"digitalWrite(LED, ledState);"的值出现跳动. 原因: ...

  6. Linux课程学习 第三课

    生活中的许多事,并不是我们不能做到,而是我们不相信能够做到 https://www.linuxcool.com/ 一个很实用的Linux命令查询网站,并且还有发音 如果我们在系统终端中执行一个命令后想 ...

  7. Mac OSX编译安装php7.1.8

    laravel中用到ldap认证包,要求php7.0以上版本,而且安装Mews\Captcha包的时候 验证码无法显示 报错如下: Call to undefined function Interve ...

  8. Codeforces Manthan, Codefest 18 (rated, Div. 1 + Div. 2) E.Trips

    比赛的时候想到怎么做了 没调出来(感觉自己是个睿智) 给你N个点M条边,这M条边是一条一条加进去的 要求你求出加入每一条边时图中极大'K度'子图的大小 极大'K度'子图的意思是 要求出一个有尽量多的点 ...

  9. document.compatMode,quirks mode and standards mode

    Document.compatMode Indicates whether the document is rendered in Quirks mode or Standards mode. Syn ...

  10. inode,软硬链接

    如何查看inode ll -di /boot / /app查看文件和文件夹的inode号 df -i查看挂载点文件夹的inode号 做inode增长实验 创建60万个文件的方法1(效率不高):for ...