8-1 jmu-java-流、文件与正则表达式
0. 字节流与二进制文件
主函数
package student;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
public class MainStream {
public static void main(String[] args)
{
String fileName="student.data";
//写入
try(DataOutputStream dos=new DataOutputStream(new FileOutputStream(fileName))){
Student stu1=new Student(50,"李",18,12);
dos.writeInt(stu1.getId());
dos.writeUTF(stu1.getName());
dos.writeInt(stu1.getAge());
dos.writeDouble(stu1.getGrade());
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
//读出
try(DataInputStream dis=new DataInputStream(new FileInputStream(fileName))){
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) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
运行结果如下
1. 字符流与文本文件:使用 PrintWriter(写),BufferedReader(读)
1.使用BufferedReader从编码为UTF-8的文本文件中读出学生信息,并组装成对象然后输出。
package student;
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.Arrays;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
String FILENAME="Students.txt";
try(BufferedReader br=new BufferedReader(new FileReader(new File(FILENAME))) ;)
{
String line=null;
while((line=br.readLine())!=null)
{
String []x=line.split("\\s+");
int id=Integer.parseInt(x[0]);
String name=x[1];
int age=Integer.parseInt(x[2]);
double grade=Double.parseDouble(x[3]);
Student stu=new Student(id,name,age,grade);
System.out.println(stu);
/*for(String e:x)
{
System.out.println(e);
}*/
}
}catch(FileNotFoundException e)
{
e.printStackTrace();
} catch(IOException e)
{
e.printStackTrace();
}
}
}
运行结果如下
2.编写public static ListreadStudents(String fileName);从fileName指定的文本文件中读取所有学生,并将其放入到一个List中
package student;
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.ArrayList;
import java.util.Arrays;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
String FILENAME="Students.txt";
ArrayList<Student> StudentList=new ArrayList<Student>();
try(BufferedReader br=new BufferedReader(new FileReader(new File(FILENAME))) ;)
{
String line=null;
while((line=br.readLine())!=null)
{
String []x=line.split("\\s+");
int id=Integer.parseInt(x[0]);
String name=x[1];
int age=Integer.parseInt(x[2]);
double grade=Double.parseDouble(x[3]);
Student stu=new Student(id,name,age,grade);
StudentList.add(stu);
//System.out.println(stu);
System.out.println(StudentList);
/*for(String e:x)
{
System.out.println(e);
}*/
}
}catch(FileNotFoundException e)
{
e.printStackTrace();
} catch(IOException e)
{
e.printStackTrace();
}
}
}
运行结果如下
3.使用PrintWriter将Student对象写入文本文件
String FILENAME="Students.txt";
ArrayList<Student> StudentList=new ArrayList<Student>();
try(FileOutputStream fos=new FileOutputStream(FILENAME,true);OutputStreamWriter osw=new OutputStreamWriter(fos,"UTF-8");PrintWriter pw=new PrintWriter(osw)){
pw.println();
pw.print("4 牛六 13 80");
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
运行结果如下
4.使用ObjectInputStream/ObjectOutputStream读写学生对象。
package student;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
public class ReadObject {
public static void main(String[] args) {
String FILENAME="Students.txt";
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) {
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) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}
2. 缓冲流(结合使用JUint进行测试)
1.使用PrintWriter往文件里写入1千万行随机整数,范围在[0,10]。随机数种子设置为100.然后从文件将每行读取出来转换成整数后相加。然后依次输出“个数 和 平均值(保留5位小数)”。
package test;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.Random;
public class Main {
public static void main(String[] args) {
String FILENAME = "test.txt";
double sum=0,aver;
PrintWriter pw=null;
try {
pw = new PrintWriter(FILENAME);
Random random=new Random();
random.setSeed(100);
for(int i = 0;i<10_000_000;i++){//写入1千万行
int r=random.nextInt(10);
sum+=r;
pw.println(r);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}finally{
pw.close();
}
aver=sum/10000000;
System.out.format("%.5f", aver);
}
}
2.使用junit对比BufferedReader与Scanner读文件的效率
package test;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.Scanner;
class Test {
String fileName = "e:/Test.txt";
@org.junit.jupiter.api.Test
void testScanner() {
//fail("Not yet implemented");
Scanner sc = null;
try {
sc = new Scanner(new File(fileName));
while(sc.hasNextLine()) {
sc.nextLine();
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
sc.close();
//System.out.println("scan end");
}
@org.junit.jupiter.api.Test
void testBufferedReader() {
//fail("Not yet implemented");
try(BufferedReader br=new BufferedReader(new FileReader(new File(fileName))) ;)
{
while((br.readLine())!=null)
{
}
}catch(FileNotFoundException e)
{
e.printStackTrace();
} catch(IOException e)
{
e.printStackTrace();
}
//System.out.println("buf end");
}
}
比较结果:BufferedReader明显更快
3. 字节流之对象流
我的代码
public static void writeStudent(List<Student> stuList)
{
String fileName="Student.dat";
try ( FileOutputStream fos=new FileOutputStream(fileName);
ObjectOutputStream ois=new ObjectOutputStream(fos))
{
ois.writeObject(stuList);
}
catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e1) {
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) {
e.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
return stuList;
}
5. 文件操作
我的代码
import java.io.File;
public class text {
static boolean flag =false;
public static void main (String[] args){
String path ="D:\\file";
String filename ="test.txt";
findFile(path,filename);
if(flag)
System.out.println("Can't find " + filename +" in "+path);
}
public static void findFile(String path,String filename)
{
File file=new File(path);
File[] files=file.listFiles();
for(File f:files)
{
for(int i=0;i<files.length;i++)
{
if(f.isFile())
{
if(f.getName().equals(filename)) System.out.println(f.getAbsolutePath());
}
else if(f.isDirectory())findFile(f.getAbsolutePath(),filename);
}
}
}
}
找出结果如下
6. 正则表达式
1.如何判断一个给定的字符串是否是10进制数字格式?尝试编程进行验证。
Scanner sc=new Scanner(System.in);
Pattern pattern=Pattern.compile("^-?[0-9]\\d*(\\.\\d+)?$");
Matcher matcher=null;
while(sc.hasNext())
{
String str=sc.next();
matcher=pattern.matcher(str);
System.out.println(matcher.matches());
}
sc.close();
2.修改HrefMatch.java
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;
/**
* This program displays all URLs in a web page by matching a regular expression that describes the
* <a href=...> HTML tag. Start the program as <br>
* java HrefMatch URL
* @version 1.01 2004-06-04
* @author Cay Horstmann
*/
public class HrefMatch
{
public static void main(String[] args)
{
try
{
// get URL string from command line or use default
String urlString;
if (args.length > 0) urlString = args[0];
else urlString = "http://cec.jmu.edu.cn";
// open reader for URL
InputStreamReader in = new InputStreamReader(new URL(urlString).openStream());
//InputStreamReader in = new InputStreamReader(new FileInputStream("集美大学-计算机工程学院.htm"));
// read contents into string builder
StringBuilder input = new StringBuilder();
int ch;
while ((ch = in.read()) != -1)
input.append((char) ch);
// search for all occurrences of pattern
String patternString = "<a\\s+href\\s*=\\s*(\"[^\"]*\"|[^\\s>]*)\\s*>";
String patternImgString = "[+-]?[0-9]+";
//String patternString = "[\u4e00-\u9fa5]"; //匹配文档中的所有中文
Pattern pattern = Pattern.compile(patternString, Pattern.CASE_INSENSITIVE);
Matcher matcher = pattern.matcher(input);
while (matcher.find())
{
int start = matcher.start();
int end = matcher.end();
String match = input.substring(start, end);
System.out.println(match);
}
}
catch (IOException e)
{
e.printStackTrace();
}
catch (PatternSyntaxException e)
{
e.printStackTrace();
}
}
}