java file 正则表达式_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 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 readStudents(String fileName)

{

List 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 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 readStudents(String fileName)

{

List stuList=new ArrayList<>();

try ( FileInputStream fis=new FileInputStream(fileName);

ObjectInputStream ois=new ObjectInputStream(fis))

{

stuList=(List)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,则输出该文件的路径

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值