First, the byte output stream
1. The method defined in OutputStream:
2.FileOutputStream类
There are many subclasses of OutputStream, and the subclass FileOutputStream can be used to write data to a file. The FileOutputStream class, the file output stream, is an output stream used to write data to File.
Examples:
import java.io.FileOutputStream;
public class demo01 {
public static void main(String[] args) throws Exception {
//如果文件不存在,会帮我们自动创建文件
FileOutputStream fos=new FileOutputStream("1.txt");
//输出
fos.write(98);
byte[] bytes={97,98,99};
fos.write(bytes);
//关闭流
fos.close();
}
}
//第二个参数,是否续写
FileOutputStream fos=new FileOutputStream("1.txt",true);
fos.write(90);
fos.close();
FileOutputStream fos=new FileOutputStream("2.txt");
//输出中文
fos.write("你好".getBytes());
//换行
fos.write("\r\n".getBytes());
fos.write("吴先生".getBytes());
fos.close();
Practice questions:
1. Copy files
import java.io.FileInputStream;
import java.io.FileOutputStream;
public class demo05_用数组复制 {
public static void main(String[] args) throws Exception {
FileInputStream fis=new FileInputStream("1.txt");
FileOutputStream fos=new FileOutputStream("4.txt");
byte[] bytes=new byte[4];
int count=0;
while((count=fis.read(bytes))!=-1){
fos.write(bytes,0,count);
}
fos.close();
fis.close();
System.out.println("复制成功!");
}
}
2. Count the number of letters in the file
import java.io.FileInputStream;
import java.util.TreeMap;
/**
* 统计一个文件中
* 字母出现的次数
* 实现思路:
* 1.读取文件,将文件内容保存到String类型的变量中
*/
public class demo06_练习题 {
public static void main(String[] args) throws Exception {
FileInputStream fis=new FileInputStream("char.txt");
byte[] bytes=new byte[10];
int count=0;
StringBuffer s=new StringBuffer();
while((count=fis.read(bytes))!=-1){
s.append(new String(bytes,0,count));
}
TreeMap<Character,Integer> treeMap=new TreeMap<>();
for(char c:s.toString().toCharArray()){
treeMap.put(c,treeMap.containsKey(c)?treeMap.get(c)+1:1);
}
System.out.println(treeMap);
}
}
Second, the byte input stream
Examples:
import java.io.FileInputStream;
import java.io.FileNotFoundException;
public class demo01 {
public static void main(String[] args) throws Exception {
FileInputStream file=new FileInputStream("test");
//读取数据,一次一个,是int 型的数据
System.out.println((char)file.read());
file.close();
//读取所有的内容
FileInputStream file1=new FileInputStream("test");
//第一种写法
/*int n=file1.read();
while(n!=-1){
System.out.print((char)n);
n=file1.read();
}*/
//第二种写法
int n1=0;
while ((n1=file1.read())!=-1){
System.out.print((char)n1);
}
file1.close();
}
}
FileInputStream file=new FileInputStream("test");
byte[] bytes=new byte[2];
int count=0;
//读取文件
while((count=file.read(bytes))!=-1){
String s=new String(bytes,0,count);
System.out.println(s);
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
/**
* 复制1.txt为3.txt
*/
public class demo04 {
public static void main(String[] args) throws Exception {
FileInputStream fis=new FileInputStream("1.txt");
FileOutputStream fos=new FileOutputStream("3.txt");
int n=0;
while((n=fis.read())!=-1){
fos.write(n);
}
fos.close();
fis.close();
System.out.println("复制成功!");
}
}
Exercises
1. Save the data in the collection to a file
import java.io.FileOutputStream;
import java.util.LinkedHashMap;
import java.util.Map;
public class demo_将集合中的数据存入文件中 {
public static void main(String[] args) throws Exception {
Map<String, Integer> map = new LinkedHashMap<>();
map.put("摩卡",30);
map.put("卡布奇诺",32);
map.put("拿铁",27);
FileOutputStream fos=new FileOutputStream("a.txt");
for(String key:map.keySet()){
fos.write(key.getBytes());
fos.write("=".getBytes());
fos.write(map.get(key).toString().getBytes());
fos.write("\r\n".getBytes());
}
fos.close();
}
}
2. Save the file to the collection
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.LinkedHashMap;
import java.util.Map;
public class demo_从文件中读取数据 {
public static void main(String[] args) throws Exception {
Map<String,Integer> map=new LinkedHashMap<>();
FileInputStream fis=new FileInputStream("a.txt");
byte[] bytes=new byte[1024];
int count=fis.read(bytes);
String str=new String(bytes,0,count);
String[] line=str.split("\r\n");
for(String k:line){
String[] s=k.split("=");
map.put(s[0],Integer.parseInt(s[1]));
}
System.out.println(map);
}
}
3. Copy the file with the specified path to the current directory
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.util.Scanner;
public class demo_练习题 {
public static void main(String[] args) throws Exception {
File file=getFile();
FileInputStream fis=new FileInputStream(file);
FileOutputStream fos=new FileOutputStream(file.getName());
byte[] bytes=new byte[10];
int count=0;
while((count=fis.read(bytes))!=-1){
fos.write(bytes,0,count);
}
fos.close();
fis.close();
System.out.println("复制成功!");
}
public static File getFile() {
Scanner sc=new Scanner(System.in);
while(true) {
System.out.print("请输入一个文件的路径:");
String path = sc.next();
File file = new File(path);
if (!file.exists()) {
System.out.println("输入路径不存在!");
} else if (file.isDirectory()) {
System.out.println("路径必须是文件!");
} else{
return file;
}
}
}
}
Three, character input stream
Examples:
import java.io.FileReader;
public class demo01 {
public static void main(String[] args) throws Exception {
//读取字符
FileReader fr=new FileReader("1.txt");
//单个读取
/*int k=0;
while((k=fr.read())!=-1){
System.out.print((char)k);
}*/
//读取到数组里面
char[] chars=new char[3];
int count=0;
while((count=fr.read(chars))!=-1){
for(int i=0;i<chars.length;i++){
System.out.print(chars[i]);
}
}
}
}
Fourth, the character output stream
Examples:
import java.io.FileWriter;
public class demo02 {
public static void main(String[] args) throws Exception {
FileWriter fw=new FileWriter("5.txt");
//写入字符串
fw.write("你好!");
//刷新
fw.flush();
//写入字符
char[] chars={'吴','先','生'};
fw.write(chars);
fw.flush();
//关闭流
fw.close();
}
}
Exercises
1. Copy the text file
import java.io.FileReader;
import java.io.FileWriter;
/**
* 使用字符流复制文本文件
*/
public class demo03 {
public static void main(String[] args) throws Exception {
FileReader fr=new FileReader("test.txt");
FileWriter fw=new FileWriter("test1.txt");
//循环读写操作效率低
/* int c=0;
while((c=fr.read())!=-1){
fw.write(c);
fw.flush();
}*/
//为了提高效率。自定义和缓冲区数组
char[] chars=new char[1024];
int len=0;
while((len=fr.read(chars))!=-1){
fw.write(chars,0,len);
}
fw.close();
fr.close();
System.out.println("复制完成!");
}
}
Five, conversion flow
Sometimes a conversion is needed between the byte stream and the character stream, in which case the conversion stream needs to be used.
Examples:
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
public class demo04 {
public static void main(String[] args) throws Exception {
//将一个字节输出流转换成字符输出流,方便字节写入字符
FileOutputStream fos=new FileOutputStream("6.txt");
//转换流
OutputStreamWriter osw=new OutputStreamWriter(fos);
osw.write("你好呀!");
osw.close();
fos.close();
}
}
Six, buffer flow
1. Byte buffer output stream
Examples:
public class Test {
public static void main(String[] args) throws IOException {
// 写数据到文件的方法
write();
}
private static void write() throws IOException {
// 创建基本的字节输出流
FileOutputStream fos = new FileOutputStream("1.txt");
// 使用高效的流,把基本的流进行封装,实现速度的提升
BufferedOutputStream bos = new BufferedOutputStream(fos);
// 2,写数据
bos.write("hello".getBytes());
// 3,关闭流
bos.close();
fos.close();
}
}
2. Byte buffer input stream
Examples:
public class Test {
public static void main(String[] args) throws IOException {
// 1. 创建缓冲流对象
FileInputStream fis = new FileInputStream("2.txt");
// 把基本的流包装成高效的流
BufferedInputStream bis = new BufferedInputStream(fis);
// 2. 读数据
int ch = -1;
while ((ch = bis.read()) != -1) {
// 打印
System.out.print((char) ch);
}
bis.close();
fis.close();
}
}
3. Character buffer stream
Examples:
import java.io.*;
public class demo2 {
public static void main(String[] args) throws Exception {
Writer fw=new FileWriter("6.txt");
BufferedWriter bw=new BufferedWriter(fw);
bw.write("吴先生");
bw.newLine();
bw.write("好久不见!");
bw.flush();
bw.close();
Reader r=new FileReader("6.txt");
BufferedReader br=new BufferedReader(r);
String s=br.readLine();
System.out.println(s);
}
}
import java.io.BufferedOutputStream;
import java.io.FileOutputStream;
public class demo1 {
public static void main(String[] args) throws Exception {
FileOutputStream fos=new FileOutputStream("1.txt");
//缓冲流
BufferedOutputStream bos=new BufferedOutputStream(fos);
bos.write(97);
bos.close();
fos.close();
}
}
Seven, object serialization flow
- Serialization: refers to the storage of an "object (including attribute values)" in a file, or transmission through the network
Class introduction: ObjectOutputStream
Construction method
ObjectOutputStream(OutputStream out)
Serialization method
void writeObject (Object obj): Write the specified object to ObjectOutputStream
Note: When an object needs to be "serialized", this class must implement: Serializable (interface)
In the Serializable interface, there is no method, this interface is called: mark interface; it is similar to a mark, if a class implements such an interface, it means that this class has a certain permission (function)
2. Deserialization: refers to converting a text file into a Java object
Class introduction: ObjectInputStream
Construction method
ObjectInputStream(InputStream in)
Deserialization method
Object readObject (): Read objects from ObjectInputStream.
Examples:
import java.io.FileOutputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
/**
*序列化
*/
public class demo1 {
public static void main(String[] args) throws Exception{
Student s=new Student("吴先生",18);
//将s对象存入文件中
ObjectOutputStream oos=new ObjectOutputStream(new FileOutputStream("student"));
//参数:要被写入的对象
oos.writeObject(s);
oos.close();
System.out.println("写入成功!");
}
}
class Student implements Serializable{
private String name;
private int age;
public Student(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
import java.io.FileInputStream;
import java.io.ObjectInputStream;
/**
* 反序列化
* 将文件中的对象读取到内存中
*/
public class demo2 {
public static void main(String[] args)throws Exception {
ObjectInputStream ois=new ObjectInputStream(new FileInputStream("student"));
//读取
Object o =ois.readObject();
//将对象转回真正的类型
Student s=(Student)o;
System.out.println(s.getName());
System.out.println(s.getAge());
}
}
Eight, print stream
PrintStream is the most convenient class to output information, mainly including byte print stream (PrintStream) and character print stream (PrintWriter). Print stream provides a very convenient printing function, you can print any data type, such as: decimal, integer , Strings, etc.
Examples:
public class Demo {
public static void main(String[] args) throws IOException {
PrintWriter out = new PrintWriter("1.txt");
out.write("你好");
out.write("\r\n");
out.write("Hello");
out.write("\r\n");
out.write("World");
out.close();
}
}