Java——流、文件与正则表达式
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——流、文件与正则表达式的更多相关文章
- java 流 文件 IO
Java 流(Stream).文件(File)和IO Java.io 包几乎包含了所有操作输入.输出需要的类.所有这些流类代表了输入源和输出目标. Java.io 包中的流支持很多种格式,比如:基本类 ...
- Java流和文件
File类:java.io包下与平台无关的文件和目录 java可以使用文件路径字符串来创建File实例,文件路径可以是绝对路径,也可以是相对路径,默认情况下,相对路径是依据用户工作路径,通常就是运行J ...
- Java 流(Stream)、文件(File)和IO
Java.io包几乎包含了所有操作输入.输出需要的类.所有这些流类代表了输入源和输出目标. Java.io包中的流支持很多种格式,比如:基本类型.对象.本地化字符集等等. 一个流可以理解为一个数据的序 ...
- Java IO 文件与流基础
Java IO 文件与流基础 @author ixenos 摘要:创建文件.文件过滤.流分类.流结构.常见流.文件流.字节数组流(缓冲区) 如何创建一个文件 #当我们调用File类的构造器时,仅仅是在 ...
- java IO文件操作简单基础入门例子,IO流其实没那么难
IO是JAVASE中非常重要的一块,是面向对象的完美体现,深入学习IO,你将可以领略到很多面向对象的思想.今天整理了一份适合初学者学习的简单例子,让大家可以更深刻的理解IO流的具体操作. 1.文件拷贝 ...
- java 中 “文件” 和 “流” 的简单分析
java 中 FIle 和 流的简单分析 File类 简单File 常用方法 创建一个File 对象,检验文件是否存在,若不存在就创建,然后对File的类的这部分操作进行演示,如文件的名称.大小等 / ...
- Java笔记:Java 流(Stream)、文件(File)和IO
更新时间:2018-1-7 12:27:21 更多请查看在线文集:http://android.52fhy.com/java/index.html java.io 包几乎包含了所有操作输入.输出需要的 ...
- Java 字符流文件读写
上篇文章,我们介绍了 Java 的文件字节流框架中的相关内容,而我们本篇文章将着重于文件字符流的相关内容. 首先需要明确一点的是,字节流处理文件的时候是基于字节的,而字符流处理文件则是基于一个个字符为 ...
- Java - 17 Java 流(Stream)、文件(File)和IO
Java 流(Stream).文件(File)和IO Java.io包几乎包含了所有操作输入.输出需要的类.所有这些流类代表了输入源和输出目标. Java.io包中的流支持很多种格式,比如:基本类型. ...
- Java总结:Java 流(Stream)、文件(File)和IO
更新时间:2018-1-7 12:27:21 更多请查看在线文集:http://android.52fhy.com/java/index.html java.io 包几乎包含了所有操作输入.输出需要的 ...
随机推荐
- Codeforces Round #603 F Economic Difficulties
题目大意 给你两棵树,结点分别是1-A与1-B,然后给了N台设备,并且A树和B树的叶子结点(两棵树的叶子节点数量相同)都是链接电机的.问,最多可以删掉几条边使得每个设备都能连到任意一棵(或两棵)树的根 ...
- MySQL两种内核对比
MySQL内核 https://blog.csdn.net/baichoufei90/article/details/83504446 关键字:全文索引 索引外置 两种内核:MyISAM 和InnoD ...
- GitFlow入门
1-概述 2-GitFLow分支介绍 2.1-master 分支 2.2-develop 分支 2.3-feature 分支 2.4-release 分支 2.5-hotfix 分支 3-GitFlo ...
- PHP之常用操作
在最高权限下执行相关命令 1)查看PHP配置 php --ini Configuration File (php.ini) Path: /www/server/php//etc Loaded Conf ...
- Chrome中的插件运用
1. Postman Java后台开发RPC,还没有没有开始和前端联调,只是想自测下这个RPC,但是有时候RPC的访问入参数据量很大,远远超过get方式访问2k(大多数浏览器通常都会限制url长度在2 ...
- python tkinter 基本使用
这里只放表格和一个控件基本属性 grid(**options) 属性-- 下方表格详细列举了各个选项的具体含义和用法: 选项 含义column 1. 指定组件插入的列(0 表示第 1 列)2. 默认值 ...
- ansible常用模块详解(三)
1.模块介绍 明确一点:模块的执行就类似是linux命令的一条命令,就单单的是为了执行一条语句,不是批量的操作,批量操作需要用到playbook内类似shell编写脚本进行批量. 1.1 模块的使用方 ...
- 标准模板库(STL)
组件: 容器:管理某类对象的集合. 迭代器:用来在一个对象集合内遍历元素. 算法:处理集合内的元素. 容器 序列式容器:顾名思义.array,vector,deque,list 和 forward_l ...
- 关于Java中线程取值并返回的方法
如何让一个线程不断跑起来,并且在取到值的时候能返回值而线程能继续跑呢? 我们都知道可以用Callable接口获得线程的返回值,或者触发事件监听来操作返回值,下面我将介绍另一种方法. public ab ...
- 最长回文子串(动规,中心扩散法,Manacher算法)
题目 leetcode:5. Longest Palindromic Substring 解法 动态规划 时间复杂度\(O(n^2)\),空间复杂度\(O(n^2)\) 基本解法直接看代码 class ...