Java学习笔记day21

文件: File

概念

File类用于描述文件或文件夹
FIle类是由JDK提供的

使用步骤

1.创建对象
2.调用方法

File的构造函数

FIle(String pathname)
	参数: 文件或文件夹所在位置
	如: 
		//表示D盘下的workspace文件夹
		File file = new File("D:\\workspace");
		
File(URI uri)
	参数: 文件或文件夹所在位置
	URI中文名: 统一资源标识符
	URL中文名: 统一资源定位符
	
	如: 
		URI uri = URI.create("D:\\workspace");
		//表示D盘下的workspace文件夹
		File file = new File(uri);
		
File(String parent, String child)
	参数: 
		parent: 上级文件夹路径
		child: 当前文件或文件夹名称
		
	如: 
		//表示D盘下的workspace文件夹
		File file = new File("D:", "workspace");
		
File(File parent, String child)
	参数: 
		parent: 上一级文件夹对象
		child: 当前文件或文件夹名称
	如: 
		//file1表示D盘
		File file1 = new File("D:");
		//file2表示D盘下的workspace文件夹
		File file2 = new File(file1, "workspace");
		
注意: 
	参数中文件或文件夹的位置可以使用相对路径,也可以使用绝对路径
	
	相对路径: 
		相对于当前项目根目录的位置
	绝对路径: 
		从盘符开始书写,直到文件或文件夹名称
特殊符号: 
	\: windows系统下的路径分隔符
	.: 当前路径
	..: 上级路径	

File属性

separator: 静态属性
	File.separator: 当前系统的路径分隔符

File的常用方法

createNewFile()
	创建文件
mkdir()
	创建一级文件夹
mkdirs()
	创建多级文件夹
delete()
	删除文件或空文件夹
exists()
	判断文件或文件夹是否存在
length()
	获取文件或文件夹字节数
	文件的字节数是文件中内容的大小
	文件夹字节数为0
getAbsolutePath()
	获取文件或文件夹的绝对路径,返回值为String
getAbsoluteFile()
	获取文件或文件夹的绝对路径,返回值为file型
getName()
	获取文件或文件夹名称
getParent()
	获取当前文件的上级文件夹路径
isFile()
	判断file对象对应的是否为文件
isDirectory()
	判断file对象对应的是否为文件夹
listFiles()
	获取当前文件夹下所有的文件与文件夹(不包含子级文件与文件夹)
listFiles(FilenameFilter filter)
listFiles(FileFilter filter)

过滤器

FileFilter: 文件过滤器
FilenameFilter: 文件名称过滤器

I/O流

作用

将程序中的数据输出(控制台,文件,网络)
或将别的地方(文件,网络)的内容输入到程序中

总结: 传输数据

分类

按流向分类
输入流: 给程序中输入数据
输出流: 将程序中的数据输出到别的地方
按传输数据的最小单位分类
字节流: 传输最小单位字节(byte)
	可以传递任何一种数据
字符流: 传输最小单位字符(char)
	只能传递文本类型的文件,如文本文档,word,...
按功能分类
节点流: 将数据直接读取或直接写入
过滤流: 在节点流的基础上增加功能

字节流

体系
InputStream: 输入字节流的顶级接口
	FileInputStream: 文件输入流
	BufferedInputStream: 字节缓冲流(输入流)
	ByteArrayInputStream: 内存流(输入流)
	ObjectInputStream: 对象流(输入流)
OutputStream: 输出字节流的顶级接口
	FileOutputStream: 文件输出流
	BufferedOutputStream: 字节缓冲流(输出流)
	ByteArrayOutputStream: 内存流(输出流)
	ObjectOutputStream: 对象流(输出流)
InputStream提供的方法
int read()
	作用: 一次最多读取一个字节,返回值就是读取到的数据,如果没有读取到数据返回-1
	
int read(byte b[])		重点
	作用: 一次读取一组字节到数组b中,最多一次可以读b数组长度个字节,返回值为读取到的字节长度,值为-1表示结束
	
int read(byte b[], int off, int len)
	作用: 一次读取一组字节到数组b中,最多可以读取len个长度的字节,返回值为读取到的字节长度,值为-1表示结束,off为本次读取的字节数据在数组b中存储开始的下标
	
void close()
	作用: 关流
OutputStream提供的方法
void write(int b)
	作用: 一次输出一字节
void write(byte b[])
	作用: 将b中的字节一次输出
void write(byte b[], int off, int len)
	作用: 将b中的字节从off位置开始输出len个
void flush()
	作用: 冲刷
void close()
	作用: 关流
文件字节流
FileInputStream
	作用: 将指定的文件中的数据读取到程序中
	构造函数: 
		FileInputStream(String name)
		参数: 
			name: 指定的文件路径
			
		FileInputStream(File file)
		参数: 
			file: 指定的文件
			
FileOutputStream
	作用: 将程序中的数据传递到指定的文件中
	构造函数: 
		FileOutputStream(File file)
		参数: 
			file: 指定的文件
			
		FileOutputStream(String name)
		参数: 
			name: 指定的文件路径
			
		FileOutputStream(File file, boolean append)
		参数: 
			file: 指定的文件
			append: 是否追加,默认值为false
		注意: 
			append为false时,如果指定文件不存在,则新建一级文件夹,如果文件存在,那么删除原有文件后,重新创建
			append为true时,如果指定文件不存在,则新建一级文件夹,如果文件存在,在原有文件尾部写入新内容
			
		FileOutputStream(String name, boolean append)
		参数: 
			name: 指定的文件路径
			append: 是否追加,默认值为false

练习

1.假设2105班有60个学生,学号为210501~210560,全部参加语文、数学、英语三门考试,给出所有同学的各科成绩
(成绩为整数、随机产生,范围为 [50,100]),并求出每位同学的总成绩。
	a、将各科成绩的第一名(并列第一取学号小的学生)的学生保存至a.txt文件中
	b、将总成绩前10名的学生信息保存至b.txt文件中
	c、将各科平均分保存至c.txt中
	d、将各科不及格的学员信息保存至d.txt中

2.歌词内容如下
Every night in my dreams
I see you I feel you
That is how I know you go on
Far across the distance
And spaces between us
You have come to show you go on
Near far
Wherever you are
I believe
That the heart does go on
Once more you open the door
And you're here in my heart
And my heart will go on and on
Love can touch us one time
And last for a lifetime
And never let go till we're gone
Love was when I loved you
One true time I hold to
In my life well always go on
Near far
Wherever you are
I believe
That the heart does go on
Once more you open the door
And you're here in my heart
And my heart will go on and on
you're here
There's nothing I fear
And I know
That my heart will go on
We'll stay forever this way
You are safe in my heart
And my heart will go on and on
        1. 将上面歌词内容存放到本地磁盘D 根目录,文件命名为 `word.txt`
        2. 选择合适的IO流读取word.txt文件的内容
        3. 统计每个单词出现的次数(单词忽略大小写)
        4. 如果出现组合单词如 `you're`按一个单词处理
        5. 将统计的结果存储到本地磁盘D根目录下的`wordcount.txt`文件
           wordcout.txt每行数据个数如下
                and 10个
                konw 20个
                
3.使用IO流完成文件的拷贝
package test01;

public class Student {
	private int id;
	private int chinese;
	private int math;
	private int english;
	
	public Student() {

	}
	
	public Student(int id, int chinese, int math, int english) {
		this.id = id;
		this.chinese = chinese;
		this.math = math;
		this.english = english;
	}

	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}

	public int getChinese() {
		return chinese;
	}

	public void setChinese(int chinese) {
		this.chinese = chinese;
	}

	public int getMath() {
		return math;
	}

	public void setMath(int math) {
		this.math = math;
	}

	public int getEnglish() {
		return english;
	}

	public void setEnglish(int english) {
		this.english = english;
	}

	@Override
	public String toString() {
		return "Student [id=" + id + ", chinese=" + chinese + ", math=" + math + ", english=" + english + "]";
	}		
}

package test01;

import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Random;

public class Test {
	public static void main(String[] args) throws IOException {
		ArrayList<Student> list = new ArrayList<Student>();
		Random random = new Random();
		int id = 210501;
		for (int i = 0; i < 60; i++, id++) {
			int chinese = random.nextInt(51) + 50;
			int math = random.nextInt(51) + 50;
			int english = random.nextInt(51) + 50;
			Student stu = new Student(id, chinese, math, english);
			list.add(stu);
		}
		//遍历
		for (Student stu : list) {
			System.out.println(stu);
		}
		
		firstScore(list);
		frontScore(list);
		averageScore(list);
		failScore(list);
	}
	
	//将各科成绩的第一名(并列第一取学号小的学生)的学生保存至a.txt文件中
	public static void firstScore(ArrayList<Student> list) throws IOException {
		Student maxChinese = list.get(0);
		for (int i = 1; i < list.size(); i++) {
			if(list.get(i).getChinese() > maxChinese.getChinese()) {
				maxChinese = list.get(i);
			}
			else if (list.get(i).getChinese() == maxChinese.getChinese() && list.get(i).getId() < maxChinese.getId()) {
				maxChinese = list.get(i);
			}
		}
		
		Student maxMath = list.get(0);
		for (int i = 1; i < list.size(); i++) {
			if(list.get(i).getMath() > maxMath.getMath()) {
				maxMath = list.get(i);
			}
			else if (list.get(i).getMath() == maxMath.getMath() && list.get(i).getId() < maxMath.getId()) {
				maxMath = list.get(i);
			}
		}
		
		Student maxEnglish = list.get(0);
		for (int i = 1; i < list.size(); i++) {
			if(list.get(i).getEnglish() > maxEnglish.getEnglish()) {
				maxEnglish = list.get(i);
			}
			else if (list.get(i).getEnglish() == maxEnglish.getEnglish() && list.get(i).getId() < maxEnglish.getId()) {
				maxEnglish = list.get(i);
			}
		}
		
		FileOutputStream fos = new FileOutputStream("a.txt");
		String str1 = maxChinese.toString() + "\n";
		String str2 = maxMath.toString() + "\n";
		String str3 = maxEnglish.toString();
		fos.write(str1.getBytes());
		fos.write(str2.getBytes());
		fos.write(str3.getBytes());
		fos.flush();
		fos.close();
	}
	
	//将总成绩前10名的学生信息保存至b.txt文件中
	public static void frontScore(ArrayList<Student> list) throws IOException {
		//先按总成绩升序排序
		Collections.sort(list, new Comparator<Student>() {

			@Override
			public int compare(Student s1, Student s2) {
				int total1 = s1.getChinese() + s1.getMath() + s1.getEnglish();
				int total2 = s2.getChinese() + s2.getMath() + s2.getEnglish();
				if(total1 != total2) {
					return total1 - total2;
				}
				return s1.getId() - s2.getId();
			}
		});
		//反转
		Collections.reverse(list);
		System.out.println("--------------------------------------------------");
		for (Student stu : list) {
			System.out.println(stu);
		}
		
		FileOutputStream fos = new FileOutputStream("b.txt");
		for(int i = 0; i < 10; i++) {
			String str = list.get(i).toString() + "\n";
			fos.write(str.getBytes());
		}
		fos.flush();
		fos.close();
	}
	
	//将各科平均分保存至c.txt中
	public static void averageScore(ArrayList<Student> list) throws IOException {
		int chineseSum = 0;
		int mathSum = 0;
		int englishSum = 0;
		for (Student stu : list) {
			chineseSum += stu.getChinese();
			mathSum += stu.getMath();
			englishSum += stu.getEnglish();
		}
		double cAverage = (double)chineseSum / 60;
		double mAverage = (double)mathSum / 60;
		double eAverage = (double)englishSum / 60;
		
		System.out.println(cAverage);
		System.out.println(mAverage);
		System.out.println(eAverage);
		String str1 = "语文平均分为: " + cAverage + "分\n";
		String str2 = "数学平均分为: " + mAverage + "分\n";
		String str3 = "英语平均分为: " + eAverage + "分\n";
		FileOutputStream fos = new FileOutputStream("c.txt");
		fos.write(str1.getBytes());
		fos.write(str2.getBytes());
		fos.write(str3.getBytes());
		fos.flush();
		fos.close();
	}
	
	//将各科不及格的学员信息保存至d.txt中
	public static void failScore(ArrayList<Student> list) throws IOException {
		ArrayList<Student> newList = new ArrayList<Student>();
		for (Student stu : list) {
			if(stu.getChinese() < 60 || stu.getMath() < 60 || stu.getEnglish() < 60) {
				newList.add(stu);
			}
		}
		
		FileOutputStream fos = new FileOutputStream("d.txt");
		for (Student stu : newList) {
			System.out.println(stu);
			String str = stu.toString() + "\n";
			fos.write(str.getBytes());
		}
		System.out.println(newList.size());
		fos.flush();
		fos.close();
	}
}

运行结果



package test02;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map.Entry;

public class Test {
	public static void main(String[] args) throws IOException {
		FileInputStream fis = new FileInputStream("D:\\word.txt");
		byte[] b = new byte[1024];
		int len = 0;
		StringBuilder sb = new StringBuilder();
		while((len = fis.read(b)) != -1) {
			String str = new String(b, 0, len);
			sb.append(str);
		}
		fis.close();
		//打印读取到的内容
		System.out.println(sb);
		String string = sb.toString();
		//转换为小写
		String lowerCaseStr = string.toLowerCase();
		//统计每个单词出现的次数
		HashMap<String, Integer> map = wordCount(lowerCaseStr);
		FileOutputStream fos = new FileOutputStream("D:\\wordcount.txt");
		for (Entry<String, Integer> entry : map.entrySet()) {
			String str = entry.getKey() + "  " + entry.getValue() + "个\n";
			fos.write(str.getBytes());
		}
		fos.flush();
		fos.close();
	}
	
	public static HashMap<String, Integer> wordCount(String article) {
		HashMap<String,Integer> map = new HashMap<String, Integer>();
		String[] words = article.split("\\s+");
//		System.out.println(Arrays.toString(words));
		for (String word : words) {
			if(map.containsKey(word)) {
				map.put(word, map.get(word) + 1);
			}
			else {
				map.put(word, 1);
			}
		}
//		for (Entry<String, Integer> entry : map.entrySet()) {
//			System.out.print(entry.getKey() + "  ");
//			System.out.println(entry.getValue() + "个");
//		}
		return map;
	}
}

运行结果

控制台上打印读取到的内容

package test03;

import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

public class Test {
	public static void main(String[] args) throws IOException {
		//将文件i.txt中的内容拷贝到j.txt文件中
		FileInputStream fis = new FileInputStream("i.txt");
		FileOutputStream fos = new FileOutputStream("j.txt");
		ByteArrayOutputStream bos = new ByteArrayOutputStream();
		byte[] b = new byte[1024];
		int len = 0;
		while((len = fis.read(b)) != -1) {
			bos.write(b, 0, len);
			bos.flush();
		}
		byte[] array = bos.toByteArray();
		fos.write(array);
		fos.flush();
		bos.close();
		fos.close();
		fis.close();
	}
}

运行结果

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值