Primeiro, o fluxo de saída de bytes
1. O método definido em OutputStream:
2.FileOutputStream 类
Existem muitas subclasses de OutputStream, e a subclasse FileOutputStream pode ser usada para gravar dados em um arquivo. A classe FileOutputStream, o fluxo de saída do arquivo, é um fluxo de saída usado para gravar dados no arquivo.
Exemplos:
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();
Questões práticas:
1. Copie arquivos
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. Conte o número de letras no arquivo
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);
}
}
Segundo, o fluxo de entrada de bytes
Exemplos:
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("复制成功!");
}
}
Exercícios
1. Salve os dados na coleção em um arquivo
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. Salve o arquivo na coleção
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. Copie o arquivo com o caminho especificado para o diretório atual
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;
}
}
}
}
Três, fluxo de entrada de caracteres
Exemplos:
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]);
}
}
}
}
Quarto, o fluxo de saída de caracteres
Exemplos:
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();
}
}
Exercícios
1. Copie o arquivo de texto
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("复制完成!");
}
}
Cinco, fluxo de conversão
Às vezes, é necessária uma conversão entre o fluxo de bytes e o fluxo de caracteres; nesse caso, o fluxo de conversão precisa ser usado.
Exemplos:
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();
}
}
Seis, fluxo de buffer
1. Fluxo de saída do buffer de bytes
Exemplos:
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. Fluxo de entrada do buffer de bytes
Exemplos:
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. Fluxo do buffer de caracteres
Exemplos:
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();
}
}
Sete, fluxo de serialização de objetos
- Serialização: refere-se ao armazenamento de um "objeto (incluindo valores de atributo)" em um arquivo ou à transmissão através da rede
Introdução à classe: ObjectOutputStream
Método de construção
ObjectOutputStream (saída OutputStream)
Método de serialização
void writeObject (Object obj): Grava o objeto especificado em ObjectOutputStream
Nota: Quando um objeto precisa ser "serializado", esta classe deve implementar: Serializable (interface)
Na interface serializável, não existe método, essa interface é chamada: interface de marca; é semelhante a uma marca, se uma classe implementa essa interface, significa que essa classe tem uma certa autoridade
2. Desserialização: refere-se à conversão de um arquivo de texto em um objeto Java
Introdução à classe: ObjectInputStream
Método de construção
ObjectInputStream (InputStream in)
Método de desserialização
Objeto readObject (): lê objetos de ObjectInputStream.
Exemplos:
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());
}
}
Oito, fluxo de impressão
PrintStream é a classe mais conveniente para a saída de informações, incluindo principalmente fluxo de impressão de bytes (PrintStream) e fluxo de impressão de caracteres (PrintWriter) .O fluxo de impressão fornece uma função de impressão muito conveniente, você pode imprimir qualquer tipo de dados, como: decimal, inteiro , Strings, etc.
Exemplos:
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();
}
}