123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599 |
- # 第一章 File类
- `java.io.File` 类是文件和目录路径名的抽象表示,主要用于文件和目录的创建、查找和删除等操作。
- File类是java.io包下代表与平台无关的文件和目录
- ## 1.1 构造方法
- | 构造器 | 描述 |
- | ----------------------------------- | ------------------------------------------------------------ |
- | `File(File parent, String child)` | 从父抽象路径名和子路径名字符串创建新的 `File`实例。 |
- | `File(String pathname)` | 通过将给定的路径名字符串转换为抽象路径名来创建新的 `File`实例。 |
- | `File(String parent, String child)` | 从父路径名字符串和子路径名字符串创建新的 `File`实例。 |
- | `File(URI uri)` | 通过将给定的 `file:` URI转换为抽象路径名来创建新的 `File`实例。 |
- 注意:
- - 一个File对象代表硬盘或网络中可能存在的一个文件或者目录。
- - 无论该路径下是否存在文件或者目录,都不影响File对象的创建。
- 示例代码如下:
- ```java
- package com.lc.file;
- import java.io.File;
- public class FileObjectTest {
- public static void main(String[] args) {
- // 文件路径名
- String pathname = "D:\\aaa.txt";
- File file1 = new File(pathname);
- // 文件路径名
- String pathname2 = "D:\\aaa\\bbb.txt";
- File file2 = new File(pathname2);
- // 通过父路径和子路径字符串
- String parent = "d:\\aaa";
- String child = "bbb.txt";
- File file3 = new File(parent, child);
- // 通过父级File对象和子路径字符串
- File parentDir = new File("d:\\aaa");
- String childFile = "bbb.txt";
- File file4 = new File(parentDir, childFile);
- }
- }
- ```
- ## 1.2 常用方法
- ### 获取判断方法
- | 方法 | 描述 |
- | ---------------------------- | ------------------------------------------------------------ |
- | public String getName() | 返回由此File表示的文件或目录的名称。 |
- | public long length() | 返回由此File表示的文件的长度。 如果此路径名表示一个目录,则返回值是不确定的。 |
- | public long lastModified() | 返回File对象对应的文件或目录的最后修改时间(毫秒值)。 |
- | public boolean exists() | 此File表示的文件或目录是否实际存在。 |
- | public boolean isDirectory() | 此File表示的是否为目录。 |
- | public boolean isFile() | 此File表示的是否为文件。 |
- | public boolean isHidden() | 此File表示的是否为隐藏文件或目录。 |
- 注意:如果File对象代表的文件或目录存在,则File对象实例初始化时,就会用硬盘中对应文件或目录的属性信息(例如,时间、类型等)为File对象的属性赋值,否则除了路径和名称,File对象的其他属性将会保留默认值。
- 示例代码如下:
- ```java
- ```
- ### 创建删除方法
- | 方法 | 描述 |
- | ---------------------------------- | -------------------------------------------------------- |
- | public boolean createNewFile**() | 当且仅当具有该名称的文件尚不存在时,创建一个新的空文件。 |
- | public boolean **delete**() | 删除由此File表示的文件或==空==目录。 |
- | public boolean mkdir() | 创建由此File表示的目录。 |
- | public boolean mkdirs() | 创建由此File表示的目录,包括任何必需但不存在的父目录。 |
- | public boolean renameTo(File dest) | 重新命名此抽象路径名表示的文件或目录。 |
- 方法演示,代码如下:
- ```java
- ```
- ### 文件列表
- | 方法 | 描述 |
- | ---------------------------------------------- | ------------------------------------------------------------ |
- | public File getParentFile() | 返回此抽象路径名父目录的抽象路径名 |
- | public File[] listFiles() | 返回一个File数组,所有的子文件或目录。 |
- | public File[] listFiles(FileFilter filter) | 返回所有满足指定过滤器的文件和目录。<br>如果给定 filter 为 null,则接受所有路径名。 |
- | public File[] listFiles(FilenameFilter filter) | 路径名满足过滤器返回true。 |
- ```java
- public class Test {
- public static void main(String[] args) {
- //打印一个文件夹里面所有的内容,打印所有文件的名字
- File file = new File("C:\\Users\\Desktop\\aaa");
- printFileName(file);
- }
- public static void printFileName(File src) {
- //1.进入文件夹
- //2,遍历数组
- //3.判断,是否为文件,如果是文件,打印名字
- //4.判断,是否为文件夹,如果是文件夹,递归
- File[] files = src.listFiles();
- for (File file : files) {
- if (file.isFile()) {
- System.out.println(file.getName());
- } else {
- //再次调用的时候,参数一定是src里面的子文件夹
- printFileName(file);
- }
- }
- }
- }
- ```
- ### 路径问题
- | 方法 | 描述 |
- | ------------------------------- | ------------------------------ |
- | public String getPath() | 将此File转换为路径名字符串。 |
- | public String getAbsolutePath() | 返回此File的绝对路径名字符串。 |
- File类可以使用文件路径字符串来创建File实例,该文件路径字符串既可以是绝对路径,也可以是相对路径。
- 默认情况下,系统总是依据用户的工作路径来解释相对路径,这个路径由系统属性“user.dir”指定,通常也就是运行Java虚拟机时所作的路径。
- * **构造路径**:使用File构造器创建File对象时指定的路径名。它可以是绝对路径,也可以是相对路径。
- * **绝对路径**:从盘符开始的路径,这是一个完整的路径。当构造路径是绝对路径时,那么getPath和getAbsolutePath结果一样。
- * **相对路径**:相对于**项目目录**的路径,这是一个便捷的路径,开发中经常使用。当构造路径是相对路径时,那么getAbsolutePath的路径 = user.dir的路径 + 构造路径
- * window的路径分隔符使用“\”,而Java程序中的“\”表示转义字符,所以在Windows中表示路径,需要用“\\”。或者直接使用“/”也可以,Java程序支持将“/”当成平台无关的路径分隔符。或者直接使用File.separator常量值表示。
- ```java
- ```
- # 第二章 IO概述
- ## 2.1 什么是IO
- Java中I/O操作主要是指使用`java.io`包下的内容,进行输入、输出操作。**输入**也叫做**读取**数据,**输出**也叫做作**写出**数据。File对象不能直接读取和写入数据,如果要操作数据,需要IO流。File对象好比是到水库的“路线地址”以及水库的描述信息(包括水库的大小、位置、建造时间等),要“存取”里面的水到你“家里”,需要“管道”,IO流就好比是管道。
- ## 2.2 IO的分类
- 根据数据的流向分为:**输入流**和**输出流**。
- - **输入流** :把数据从`其他设备`上读取到`内存`中的流。
- - **输出流** :把数据从`内存` 中写出到`其他设备`上的流。
- 格局数据的类型分为:**字节流**和**字符流**。
- - **字节流** :以字节为单位,读写数据的流。
- - **字符流** :以字符为单位,读写数据的流。
- ## 2.3 四大顶级抽象父类
- | | **输入流** | 输出流 |
- | :--------: | :-----------------------: | :------------------------: |
- | **字符流** | 字符输入流**Reader** | 字符输出流**Writer** |
- | **字节流** | 字节输入流**InputStream** | 字节输出流**OutputStream** |
- # 第三章 字节流
- ## 3.1 一切皆为字节
- 一切文件数据(文本、图片、视频等)在存储时,都是以二进制数字的形式保存,都一个一个的字节,那么传输时一样如此。所以,字节流可以传输任意文件数据。在操作流的时候,我们要时刻明确,无论使用什么样的流对象,底层传输的始终为二进制数据。
- ## 3.2 字节输出流【OutputStream抽象类】
- `java.io.OutputStream `抽象类是表示字节输出流的所有类的超类,将指定的字节信息写出到目的地。它定义了字节输出流的基本共性功能方法。
- - `public void close()` :关闭此输出流并释放与此流相关联的任何系统资源。
- - `public void flush() ` :刷新此输出流并强制任何缓冲的输出字节被写出。
- - `public void write(byte[] b)`:将 b.length字节从指定的字节数组写入此输出流。
- - `public void write(byte[] b, int off, int len)` :从指定的字节数组写入 len字节,从偏移量 off开始输出到此输出流。
- - `public abstract void write(int b)` :将指定的字节输出流。
- > 小贴士:
- >
- > close方法,当完成流的操作时,必须调用此方法,释放系统资源。
- ## 3.3 FileOutputStream类(实现类)
- `OutputStream`有很多子类,我们从最简单的一个子类开始。
- `java.io.FileOutputStream `类是文件输出流,用于将数据写出到文件。
- ### 构造方法
- - `public FileOutputStream(File file)`:创建文件输出流以写入由指定的 File对象表示的文件。
- - `public FileOutputStream(String name)`: 创建文件输出流以指定的名称写入文件。
- 当你创建一个流对象时,必须传入一个文件路径。该路径下,如果没有这个文件,会创建该文件。如果有这个文件,会清空这个文件的数据。
- - 构造举例,代码如下:
- ```java
- public class FileOutputStreamConstructor throws IOException {
- public static void main(String[] args) {
- // 使用File对象创建流对象
- File file = new File("a.txt");
- FileOutputStream fos = new FileOutputStream(file);
- // 使用文件名称创建流对象
- FileOutputStream fos = new FileOutputStream("b.txt");
- }
- }
- ```
- ### 写出字节数据
- 1. **写出字节**:`write(int b)` 方法,每次可以写出一个字节数据,代码使用演示:
- ```java
- public class FOSWrite {
- public static void main(String[] args) throws IOException {
- // 使用文件名称创建流对象
- FileOutputStream fos = new FileOutputStream("fos.txt");
- // 写出数据
- fos.write(97); // 写出第1个字节
- fos.write(98); // 写出第2个字节
- fos.write(99); // 写出第3个字节
- // 关闭资源
- fos.close();
- }
- }
- 输出结果:
- abc
- ```
- > 小贴士:
- >
- > 1. 虽然参数为int类型四个字节,但是只会保留一个字节的信息写出。
- > 2. 流操作完毕后,必须释放系统资源,调用close方法,千万记得。
- 1. **写出字节数组**:`write(byte[] b)`,每次可以写出数组中的数据,代码使用演示:
- ```java
- public class FOSWrite {
- public static void main(String[] args) throws IOException {
- // 使用文件名称创建流对象
- FileOutputStream fos = new FileOutputStream("fos.txt");
- // 字符串转换为字节数组
- byte[] b = "爱扣钉".getBytes();
- // 写出字节数组数据
- fos.write(b);
- // 关闭资源
- fos.close();
- }
- }
- 输出结果:
- 爱扣钉
- ```
- 1. **写出指定长度字节数组**:`write(byte[] b, int off, int len)` ,每次写出从off索引开始,len个字节,代码使用演示:
- ```java
- public class FOSWrite {
- public static void main(String[] args) throws IOException {
- // 使用文件名称创建流对象
- FileOutputStream fos = new FileOutputStream("fos.txt");
- // 字符串转换为字节数组
- byte[] b = "abcde".getBytes();
- // 写出从索引2开始,2个字节。索引2是c,两个字节,也就是cd。
- fos.write(b,2,2);
- // 关闭资源
- fos.close();
- }
- }
- 输出结果:
- cd
- ```
- ### 数据追加
- 经过以上的演示,每次程序运行,创建输出流对象,都会清空目标文件中的数据。如何保留目标文件中数据,还能继续添加新数据呢?
- - `public FileOutputStream(File file, boolean append)`: 创建文件输出流以写入由指定的 File对象表示的文件。
- - `public FileOutputStream(String name, boolean append)`: 创建文件输出流以指定的名称写入文件。
- 这两个构造方法,参数中都需要传入一个boolean类型的值,`true` 表示追加数据,`false` 表示清空原有数据。这样创建的输出流对象,就可以指定是否追加续写了,代码使用演示:
- ```java
- public class FOSWrite {
- public static void main(String[] args) throws IOException {
- // 使用文件名称创建流对象
- FileOutputStream fos = new FileOutputStream("fos.txt",true);
- // 字符串转换为字节数组
- byte[] b = "abcde".getBytes();
- // 写出从索引2开始,2个字节。索引2是c,两个字节,也就是cd。
- fos.write(b);
- // 关闭资源
- fos.close();
- }
- }
- 文件操作前:cd
- 文件操作后:cdabcde
- ```
- ## 3.4 字节输入流【InputStream】
- `java.io.InputStream `抽象类是表示字节输入流的所有类的超类,可以读取字节信息到内存中。它定义了字节输入流的基本共性功能方法。
- - `public void close()` :关闭此输入流并释放与此流相关联的任何系统资源。
- - `public abstract int read()`: 从输入流读取数据的下一个字节。
- - `public int read(byte[] b)`: 从输入流中读取一些字节数,并将它们存储到字节数组 b中 。
- > 小贴士:
- >
- > close方法,当完成流的操作时,必须调用此方法,释放系统资源。
- ## 3.5 FileInputStream类
- `java.io.FileInputStream `类是文件输入流,从文件中读取字节。
- ### 构造方法
- - `FileInputStream(File file)`: 通过打开与实际文件的连接来创建一个 FileInputStream ,该文件由文件系统中的 File对象 file命名。
- - `FileInputStream(String name)`: 通过打开与实际文件的连接来创建一个 FileInputStream ,该文件由文件系统中的路径名 name命名。
- 当你创建一个流对象时,必须传入一个文件路径。该路径下,如果没有该文件,会抛出`FileNotFoundException`
- - 构造举例,代码如下:
- ```java
- public class FileInputStreamConstructor throws IOException{
- public static void main(String[] args) {
- // 使用File对象创建流对象
- File file = new File("a.txt");
- FileInputStream fos = new FileInputStream(file);
- // 使用文件名称创建流对象
- FileInputStream fos = new FileInputStream("b.txt");
- }
- }
- ```
- ### 读取字节数据
- 1. **读取字节**:`read`方法,每次可以读取一个字节的数据,提升为int类型,读取到文件末尾,返回`-1`,代码使用演示:
- ```java
- public class FISRead {
- public static void main(String[] args) throws IOException{
- // 使用文件名称创建流对象
- FileInputStream fis = new FileInputStream("read.txt");
- // 读取数据,返回一个字节
- int read = fis.read();
- System.out.println((char) read);
- read = fis.read();
- System.out.println((char) read);
- read = fis.read();
- System.out.println((char) read);
- read = fis.read();
- System.out.println((char) read);
- read = fis.read();
- System.out.println((char) read);
- // 读取到末尾,返回-1
- read = fis.read();
- System.out.println( read);
- // 关闭资源
- fis.close();
- }
- }
- 输出结果:
- a
- b
- c
- d
- e
- -1
- ```
- 循环改进读取方式,代码使用演示:
- ```java
- public class FISRead {
- public static void main(String[] args) throws IOException{
- // 使用文件名称创建流对象
- FileInputStream fis = new FileInputStream("read.txt");
- // 定义变量,保存数据
- int b ;
- // 循环读取
- while ((b = fis.read())!=-1) {
- System.out.println((char)b);
- }
- // 关闭资源
- fis.close();
- }
- }
- 输出结果:
- a
- b
- c
- d
- e
- ```
- > 小贴士:
- >
- > 1. 虽然读取了一个字节,但是会自动提升为int类型。
- > 2. 流操作完毕后,必须释放系统资源,调用close方法,千万记得。
- 1. **使用字节数组读取**:`read(byte[] b)`,每次读取b的长度个字节到数组中,返回读取到的有效字节个数,读取到末尾时,返回`-1` ,代码使用演示:
- ```java
- public class FISRead {
- public static void main(String[] args) throws IOException{
- // 使用文件名称创建流对象.
- FileInputStream fis = new FileInputStream("read.txt"); // 文件中为abcde
- // 定义变量,作为有效个数
- int len ;
- // 定义字节数组,作为装字节数据的容器
- byte[] b = new byte[2];
- // 循环读取
- while (( len= fis.read(b))!=-1) {
- // 每次读取后,把数组变成字符串打印
- System.out.println(new String(b));
- }
- // 关闭资源
- fis.close();
- }
- }
- 输出结果:
- ab
- cd
- ed
- ```
- 错误数据`d`,是由于最后一次读取时,只读取一个字节`e`,数组中,上次读取的数据没有被完全替换,所以要通过`len` ,获取有效的字节,代码使用演示:
- ```java
- public class FISRead {
- public static void main(String[] args) throws IOException{
- // 使用文件名称创建流对象.
- FileInputStream fis = new FileInputStream("read.txt"); // 文件中为abcde
- // 定义变量,作为有效个数
- int len ;
- // 定义字节数组,作为装字节数据的容器
- byte[] b = new byte[2];
- // 循环读取
- while (( len= fis.read(b))!=-1) {
- // 每次读取后,把数组的有效字节部分,变成字符串打印
- System.out.println(new String(b,0,len));// len 每次读取的有效字节个数
- }
- // 关闭资源
- fis.close();
- }
- }
- 输出结果:
- ab
- cd
- e
- ```
- > 小贴士:
- >
- > 使用数组读取,每次读取多个字节,减少了系统间的IO操作次数,从而提高了读写的效率,建议开发中使用。
- ## 3.6 复制文件
- 一切文件数据(文本、图片、视频等)在存储时,都是以二进制数字的形式保存,都一个一个的字节,那么传输时一样如此。所以,字节流可以传输任意文件数据。在操作流的时候,我们要时刻明确,无论使用什么样的流对象,底层传输的始终为二进制数据。
- 
- 复制图片文件,代码使用演示:
- ```java
- package com.lc.fileio;
- import java.io.FileInputStream;
- import java.io.FileOutputStream;
- import java.io.IOException;
- public class FileCopy {
- public static void main(String[] args) throws IOException {
- // 1.创建流对象
- // 1.1 指定数据源
- FileInputStream fis = new FileInputStream("D:\\test.jpg");
- // 1.2 指定目的地
- FileOutputStream fos = new FileOutputStream("test_copy.jpg");
- // 2.读写数据
- // 2.1 定义数组
- byte[] b = new byte[1024];
- // 2.2 定义长度
- int len;
- // 2.3 循环读取
- while ((len = fis.read(b))!=-1) {
- // 2.4 写出数据
- fos.write(b, 0 , len);
- }
- // 3.关闭资源
- fos.close();
- fis.close();
- }
- }
- ```
- # 第四章 字符流
- 当使用字节流读取文本文件时,可能会有一个小问题。就是遇到中文字符时,可能不会显示完整的字符,那是因为一个中文字符可能占用多个字节存储。所以Java提供一些字符流类,以字符为单位读写数据,专门用于处理文本文件。
- ## 4.1 字符输入流【Reader】
- `java.io.Reader`抽象类是表示用于读取字符流的所有类的超类,可以读取字符信息到内存中。它定义了字符输入流的基本共性功能方法。
- - `public void close()` :关闭此流并释放与此流相关联的任何系统资源。
- - `public int read()`: 从输入流读取一个字符。
- - `public int read(char[] cbuf)`: 从输入流中读取一些字符,并将它们存储到字符数组 cbuf中 。
- ## 4.2 FileReader类
- `java.io.FileReader `类是读取字符文件的便利类。构造时使用系统默认的字符编码。
- > 小贴士:
- >
- > 1. 字符编码:字节与字符的对应规则。Windows系统的中文编码默认是GBK编码表。
- >
- > idea中UTF-8
- ### 构造方法
- - `FileReader(File file)`: 创建一个新的 FileReader ,给定要读取的File对象。
- - `FileReader(String fileName)`: 创建一个新的 FileReader ,给定要读取的文件的名称。
- 当你创建一个流对象时,必须传入一个文件路径。类似于FileInputStream 。
- - 构造举例,代码如下:
- ```java
- public class FileReaderConstructor throws IOException{
- public static void main(String[] args) {
- // 使用File对象创建流对象
- File file = new File("a.txt");
- FileReader fr = new FileReader(file);
- // 使用文件名称创建流对象
- FileReader fr = new FileReader("b.txt");
- }
- }
- ```
- ### 读取字符数据
- 1. **读取字符**:`read`方法,每次可以读取一个字符的数据,提升为int类型,读取到文件末尾,返回`-1`,循环读取,代码使用演示:
- ```java
- public class FRRead {
- public static void main(String[] args) throws IOException {
- // 使用文件名称创建流对象
- FileReader fr = new FileReader("read.txt");
- // 定义变量,保存数据
- int b ;
- // 循环读取
- while ((b = fr.read())!=-1) {
- System.out.println((char)b);
- }
- // 关闭资源
- fr.close();
- }
- }
- 输出结果:
- 黑
- 马
- 程
- 序
- 员
- ```
- > 小贴士:虽然读取了一个字符,但是会自动提升为int类型。
- 1. **使用字符数组读取**:`read(char[] cbuf)`,每次读取b的长度个字符到数组中,返回读取到的有效字符个数,读取到末尾时,返回`-1` ,代码使用演示:
- ```java
- public class FRRead {
- public static void main(String[] args) throws IOException {
- // 使用文件名称创建流对象
- FileReader fr = new FileReader("read.txt");
- // 定义变量,保存有效字符个数
- int len ;
- // 定义字符数组,作为装字符数据的容器
- char[] cbuf = new char[2];
- // 循环读取
- while ((len = fr.read(cbuf))!=-1) {
- System.out.println(new String(cbuf));
- }
- // 关闭资源
- fr.close();
- }
- }
- 输出结果:
- 黑马
- 程序
- 员序
- ```
- 获取有效的字符改进,代码使用演示:
- ```java
- public class FISRead {
- public static void main(String[] args) throws IOException {
- // 使用文件名称创建流对象
- FileReader fr = new FileReader("read.txt");
- // 定义变量,保存有效字符个数
- int len ;
- // 定义字符数组,作为装字符数据的容器
- char[] cbuf = new char[2];
- // 循环读取
- while ((len = fr.read(cbuf))!=-1) {
- System.out.println(new String(cbuf,0,len));
- }
- // 关闭资源
- fr.close();
- }
- }
- 输出结果:
- 黑马
- 程序
- 员
- ```
- ## 4.3 字符输出流【Writer】
- `java.io.Writer `抽象类是表示用于写出字符流的所有类的超类,将指定的字符信息写出到目的地。它定义了字节输出流的基本共性功能方法。
- - `public abstract void close()` :关闭此输出流并释放与此流相关联的任何系统资源。
- - `public abstract void flush() ` :刷新此输出流并强制任何缓冲的输出字符被写出。
- - `public void write(int c)` :写出一个字符。
- - `public void write(char[] cbuf)`:将 b.length字符从指定的字符数组写出此输出流。
- - `public abstract void write(char[] b, int off, int len)` :从指定的字符数组写出 len字符,从偏移量 off开始输出到此输出流。
- - `public void write(String str)` :写出一个字符串。
- ## 4.4 FileWriter类
- `java.io.FileWriter `类是写出字符到文件的便利类。构造时使用系统默认的字符编码。
- ### 构造方法
- - `FileWriter(File file)`: 创建一个新的 FileWriter,给定要读取的File对象。
- - `FileWriter(String fileName)`: 创建一个新的 FileWriter,给定要读取的文件的名称。
- 当你创建一个流对象时,必须传入一个文件路径,类似于FileOutputStream。
- - 构造举例,代码如下:
- ```java
- public class FileWriterConstructor {
- public static void main(String[] args) throws IOException {
- // 使用File对象创建流对象
- File file = new File("a.txt");
- FileWriter fw = new FileWriter(file);
- // 使用文件名称创建流对象
- FileWriter fw = new FileWriter("b.txt");
- }
- }
- ```
- ### 基本写出数据
- **写出字符**:`write(int b)` 方法,每次可以写出一个字符数据,代码使用演示:
- ```java
- public class FWWrite {
- public static void main(String[] args) throws IOException {
- // 使用文件名称创建流对象
- FileWriter fw = new FileWriter("fw.txt");
- // 写出数据
- fw.write(97); // 写出第1个字符
- fw.write('b'); // 写出第2个字符
- fw.write('C'); // 写出第3个字符
- fw.write(30000); // 写出第4个字符,中文编码表中30000对应一个汉字。
- /*
- 【注意】流最后都要释放资源
- */
- fw.close();
- }
- }
- 输出结果:
- abC田
- ```
- > 小贴士:
- >
- > 1. 虽然参数为int类型四个字节,但是只会保留一个字符的信息写出。
- ### 写出其他数据
- 1. **写出字符数组** :`write(char[] cbuf)` 和 `write(char[] cbuf, int off, int len)` ,每次可以写出字符数组中的数据,用法类似FileOutputStream,代码使用演示:
- ```java
- public class FWWrite {
- public static void main(String[] args) throws IOException {
- // 使用文件名称创建流对象
- FileWriter fw = new FileWriter("fw.txt");
- // 字符串转换为字节数组
- char[] chars = "黑马程序员".toCharArray();
- // 写出字符数组
- fw.write(chars); // 黑马程序员
- // 写出从索引2开始,2个字节。索引2是'程',两个字节,也就是'程序'。
- fw.write(b,2,2); // 程序
- // 关闭资源
- fos.close();
- }
- }
- ```
- 1. **写出字符串**:`write(String str)` 和 `write(String str, int off, int len)` ,每次可以写出字符串中的数据,更为方便,代码使用演示:
- ```java
- public class FWWrite {
- public static void main(String[] args) throws IOException {
- // 使用文件名称创建流对象
- FileWriter fw = new FileWriter("fw.txt");
- // 字符串
- String msg = "黑马程序员";
- // 写出字符数组
- fw.write(msg); //黑马程序员
- // 写出从索引2开始,2个字节。索引2是'程',两个字节,也就是'程序'。
- fw.write(msg,2,2); // 程序
- // 关闭资源
- fos.close();
- }
- }
- ```
- 1. **续写和换行**:操作类似于FileOutputStream。
- ```java
- public class FWWrite {
- public static void main(String[] args) throws IOException {
- // 使用文件名称创建流对象,可以续写数据
- FileWriter fw = new FileWriter("fw.txt",true);
- // 写出字符串
- fw.write("黑马");
- // 写出换行
- fw.write("\r\n");
- // 写出字符串
- fw.write("程序员");
- // 关闭资源
- fw.close();
- }
- }
- 输出结果:
- 黑马
- 程序员
- ```
- > 小贴士:字符流,只能操作文本文件,不能操作图片,视频等非文本文件。
- >
- > 当我们单纯读或者写文本文件时 使用字符流 其他情况使用字节流
- ## 4.5练习:键盘录入数据并写到文件
- 需求:
- 从控制台循环接收用户录入的学生信息,
- 输入格式为:学号-学生名字
- 将学生信息保存到C盘下面的stu.txt文件中,
- 一个学生信息占据一行数据。
- 当用户输入end时停止输入。
- 代码示例:
- ```java
- //如果使用字节流不符合我们使用的规范
- //字节流:只做拷贝
- //字符流:做纯文本文件的读 和 写
- FileWriter fw = new FileWriter("day09-code\\a.txt");
- Scanner sc = new Scanner(System.in);
- while (true) {
- System.out.println("请输入学生信息");
- String str = sc.nextLine();
- if("end".equals(str)){
- break;
- }
- fw.write(str);
- fw.write("\r\n");
- }
- fw.close();
- ```
- # 第五章 缓冲流
- 缓冲流,也叫高效流,按照数据类型分类:
- * **字节缓冲流**:`BufferedInputStream`,`BufferedOutputStream`
- * **字符缓冲流**:`BufferedReader`,`BufferedWriter`
- 缓冲流的基本原理,是在创建流对象时,会创建一个内置的默认大小的缓冲区数组,通过缓冲区读写,减少系统IO次数,从而提高读写的效率。
- ## 5.1 构造方法
- * `public BufferedInputStream(InputStream in)` :创建一个 新的缓冲输入流。
- * `public BufferedOutputStream(OutputStream out)`: 创建一个新的缓冲输出流。
- 构造举例,代码如下:
- ```java
- // 创建字节缓冲输入流
- BufferedInputStream bis = new BufferedInputStream(new FileInputStream("bis.txt"));
- // 创建字节缓冲输出流
- BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("bos.txt"));
- ```
- * `public BufferedReader(Reader in)` :创建一个 新的缓冲输入流。
- * `public BufferedWriter(Writer out)`: 创建一个新的缓冲输出流。
- 构造举例,代码如下:
- ```java
- // 创建字符缓冲输入流
- BufferedReader br = new BufferedReader(new FileReader("br.txt"));
- // 创建字符缓冲输出流
- BufferedWriter bw = new BufferedWriter(new FileWriter("bw.txt"));
- ```
- ## 5.2 效率测试
- 查询API,缓冲流读写方法与基本的流是一致的,我们通过复制大文件(375MB),测试它的效率。
- ```java
- package com.lc.buffer;
- import org.junit.Test;
- import java.io.*;
- public class BufferedIO {
- @Test
- public void testNoBuffer() throws IOException {
- // 记录开始时间
- long start = System.currentTimeMillis();
- // 创建流对象
- FileInputStream fis = new FileInputStream("jdk8.exe");
- FileOutputStream fos = new FileOutputStream("copy.exe");
- // 读写数据
- byte[] data = new byte[1024];
- int len;
- while ((len = fis.read(data)) != -1) {
- fos.write(data,0,len);
- }
- fos.close();
- fis.close();
- // 记录结束时间
- long end = System.currentTimeMillis();
- System.out.println("普通流复制时间:"+(end - start)+" 毫秒");
- }
- @Test
- public void testUseBuffer() throws IOException {
- // 记录开始时间
- long start = System.currentTimeMillis();
- // 创建流对象
- BufferedInputStream bis = new BufferedInputStream(new FileInputStream("jdk8.exe"));
- BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("copy.exe"));
- // 读写数据
- int len;
- byte[] data = new byte[1024];
- while ((len = bis.read(data)) != -1) {
- bos.write(data, 0 , len);
- }
- bos.close();
- bis.close();
- // 记录结束时间
- long end = System.currentTimeMillis();
- System.out.println("缓冲流使用数组复制时间:"+(end - start)+" 毫秒");
- }
- }
- ```
- ## 5.3 字符缓冲流特有方法
- 字符缓冲流的基本方法与普通字符流调用方式一致,不再阐述,我们来看它们具备的特有方法。
- * BufferedReader:`public String readLine()`: 读一行文字。
- * BufferedWriter:`public void newLine()`: 写一行行分隔符,由系统属性定义符号。
- ```java
- package com.lc.buffer;
- import org.junit.Test;
- import java.io.*;
- public class BufferedIOLine {
- @Test
- public void testReadLine()throws IOException {
- // 创建流对象
- BufferedReader br = new BufferedReader(new FileReader("in.txt"));
- // 定义字符串,保存读取的一行文字
- String line;
- // 循环读取,读取到最后返回null
- while ((line = br.readLine())!=null) {
- System.out.println(line);
- }
- // 释放资源
- br.close();
- }
- @Test
- public void testNewLine()throws IOException{
- // 创建流对象
- BufferedWriter bw = new BufferedWriter(new FileWriter("out.txt"));
- // 写出数据
- bw.write("尚");
- // 写出换行
- bw.newLine();
- bw.write("硅");
- bw.newLine();
- bw.write("谷");
- bw.newLine();
- // 释放资源
- bw.close();
- }
- }
- ```
- ## 5.4 流的关闭顺序
- ```java
- package com.lc.buffer;
- import org.junit.Test;
- import java.io.BufferedWriter;
- import java.io.FileWriter;
- import java.io.IOException;
- public class IOClose {
- @Test
- public void test01() throws IOException {
- FileWriter fw = new FileWriter("d:/1.txt");
- BufferedWriter bw = new BufferedWriter(fw);
- bw.write("hello");
- fw.close();
- bw.close();//java.io.IOException: Stream closed
- /*
- 先写到bw(缓冲区)=>fw =>"文件"
- 先把fw关闭了,bw的数据无法输出了
- 1221 的顺序
- */
- }
- }
- ```
- ## 练习:文本排序
- 请将文本信息恢复顺序。
- ```
- 3.侍中、侍郎郭攸之、费祎、董允等,此皆良实,志虑忠纯,是以先帝简拔以遗陛下。愚以为宫中之事,事无大小,悉以咨之,然后施行,必得裨补阙漏,有所广益。
- 8.愿陛下托臣以讨贼兴复之效,不效,则治臣之罪,以告先帝之灵。若无兴德之言,则责攸之、祎、允等之慢,以彰其咎;陛下亦宜自谋,以咨诹善道,察纳雅言,深追先帝遗诏,臣不胜受恩感激。
- 4.将军向宠,性行淑均,晓畅军事,试用之于昔日,先帝称之曰能,是以众议举宠为督。愚以为营中之事,悉以咨之,必能使行阵和睦,优劣得所。
- 2.宫中府中,俱为一体,陟罚臧否,不宜异同。若有作奸犯科及为忠善者,宜付有司论其刑赏,以昭陛下平明之理,不宜偏私,使内外异法也。
- 1.先帝创业未半而中道崩殂,今天下三分,益州疲弊,此诚危急存亡之秋也。然侍卫之臣不懈于内,忠志之士忘身于外者,盖追先帝之殊遇,欲报之于陛下也。诚宜开张圣听,以光先帝遗德,恢弘志士之气,不宜妄自菲薄,引喻失义,以塞忠谏之路也。
- 9.今当远离,临表涕零,不知所言。
- 6.臣本布衣,躬耕于南阳,苟全性命于乱世,不求闻达于诸侯。先帝不以臣卑鄙,猥自枉屈,三顾臣于草庐之中,咨臣以当世之事,由是感激,遂许先帝以驱驰。后值倾覆,受任于败军之际,奉命于危难之间,尔来二十有一年矣。
- 7.先帝知臣谨慎,故临崩寄臣以大事也。受命以来,夙夜忧叹,恐付托不效,以伤先帝之明,故五月渡泸,深入不毛。今南方已定,兵甲已足,当奖率三军,北定中原,庶竭驽钝,攘除奸凶,兴复汉室,还于旧都。此臣所以报先帝而忠陛下之职分也。至于斟酌损益,进尽忠言,则攸之、祎、允之任也。
- 5.亲贤臣,远小人,此先汉所以兴隆也;亲小人,远贤臣,此后汉所以倾颓也。先帝在时,每与臣论此事,未尝不叹息痛恨于桓、灵也。侍中、尚书、长史、参军,此悉贞良死节之臣,愿陛下亲之信之,则汉室之隆,可计日而待也。
- ```
- 实现步骤
- 1. 逐行读取文本信息。
- 2. 解析文本信息到集合中。
- 3. 遍历集合,按顺序,写出文本信息。
- ```java
- public class Test07 {
- public static void main(String[] args) throws IOException {
- //1.定义一个TreeMap 键:序号 值:内容
- //默认是按照键来排序的
- //Integer默认的排序规则:升序
- TreeMap<Integer, String> tm = new TreeMap<>();
- //2.把所有的数据读到内存中
- BufferedReader br = new BufferedReader(new FileReader("a.txt"));
- //3.循环读取,并存入集合
- //细节:readLine在读取的时候,遇到回车换行符就停止了。
- //但是不会读回车换行
- String line;
- while ((line = br.readLine()) != null) {
- String[] info = line.split("\\.");
- int key = Integer.parseInt(info[0]);
- String value = info[1];
- tm.put(key, value);
- }
- //4.释放资源
- //什么时候不用了,随手就释放掉
- br.close();
- //5.遍历集合,把数据写到新的文件中
- BufferedWriter bw = new BufferedWriter(new FileWriter("result.txt"));
- Set<Integer> keys = tm.keySet();
- for (int key : keys) {
- String value = tm.get(key);
- bw.write(key + "." + value);
- bw.newLine();
- //写一行就刷新一下
- bw.flush();
- }
- //6.释放资源
- bw.close();
- }
- }
- ```
- # 第六章 转换流
- ## 6.1 字符编码和字符集
- ### 1、编码与解码
- 计算机中储存的信息都是用二进制数表示的,而我们在屏幕上看到的数字、英文、标点符号、汉字等字符是二进制数转换之后的结果。按照某种规则,将字符存储到计算机中,称为**编码** 。反之,将存储在计算机中的二进制数按照某种规则解析显示出来,称为**解码** 。比如说,按照A规则存储,同样按照A规则解析,那么就能显示正确的文本符号。反之,按照A规则存储,再按照B规则解析,就会导致乱码现象。
- * **字符编码`Character Encoding`** : 就是一套自然语言的字符与二进制数之间的对应规则。
- * **编码表**:生活中文字和计算机中二进制的对应规则
- ### 2、字符编码与字符集
- * **字符集 `Charset`**:也叫编码表。是一个系统支持的所有字符的集合,包括各国家文字、标点符号、图形符号、数字等。
- 计算机要准确的存储和识别各种字符集符号,需要进行字符编码,一套字符集必然至少有一套字符编码。常见字符集有ASCII字符集、GBK字符集、Unicode字符集等。
- * **Unicode字符集** :
- 
- * Unicode编码系统为表达任意语言的任意字符而设计,是业界的一种标准,也称为统一码、标准万国码。
- * 它最多使用4个字节的数字来表达每个字母、符号,或者文字。有三种编码方案,UTF-8、UTF-16和UTF-32。最为常用的UTF-8编码。
- * UTF-8编码,可以用来表示Unicode标准中任何字符,它是电子邮件、网页及其他存储或传送文字的应用中,优先采用的编码。互联网工程工作小组(IETF)要求所有互联网协议都必须支持UTF-8编码。所以,我们开发Web应用,也要使用UTF-8编码。它使用一至四个字节为每个字符编码,编码规则:
- 1. 128个US-ASCII字符,只需一个字节编码。
- 2. 拉丁文等字符,需要二个字节编码。
- 3. 大部分常用字(含中文),使用三个字节编码。
- 4. 其他极少使用的Unicode辅助字符,使用四字节编码。
- ## 6.2 编码引出的问题
- 使用`FileReader` 读取项目中的文本文件。由于项目设置了UTF-8编码,当读取Windows系统中创建的文本文件时,由于Windows系统的默认是GBK编码,就会出现乱码。
- ```java
- package com.lc.transfer;
- import java.io.FileReader;
- import java.io.IOException;
- public class Problem {
- public static void main(String[] args) throws IOException {
- FileReader fileReader = new FileReader("E:\\File_GBK.txt");
- int read;
- while ((read = fileReader.read()) != -1) {
- System.out.print((char)read);
- }
- fileReader.close();
- }
- }
- 输出结果:
- ���
- ```
- 那么如何读取GBK编码的文件呢?
- ## 6.3 InputStreamReader类
- 转换流`java.io.InputStreamReader`,是Reader的子类,是从字节流到字符流的桥梁。它读取字节,并使用指定的字符集将其解码为字符。它的字符集可以由名称指定,也可以接受平台的默认字符集。
- * `InputStreamReader(InputStream in)`: 创建一个使用默认字符集的字符流。
- * `InputStreamReader(InputStream in, String charsetName)`: 创建一个指定字符集的字符流。
- 构造举例,代码如下:
- ```java
- InputStreamReader isr = new InputStreamReader(new FileInputStream("in.txt"));
- InputStreamReader isr2 = new InputStreamReader(new FileInputStream("in.txt") , "GBK");
- ```
- 示例代码:
- ```java
- package com.lc.transfer;
- import java.io.FileInputStream;
- import java.io.IOException;
- import java.io.InputStreamReader;
- public class InputStreamReaderDemo {
- public static void main(String[] args) throws IOException {
- // 定义文件路径,文件为gbk编码
- String fileName = "E:\\file_gbk.txt";
- // 创建流对象,默认UTF8编码
- InputStreamReader isr1 = new InputStreamReader(new FileInputStream(fileName));
- // 定义变量,保存字符
- int charData;
- // 使用默认编码字符流读取,乱码
- while ((charData = isr1.read()) != -1) {
- System.out.print((char)charData); // ��Һ�
- }
- isr1.close();
- // 创建流对象,指定GBK编码
- InputStreamReader isr2 = new InputStreamReader(new FileInputStream(fileName) , "GBK");
- // 使用指定编码字符流读取,正常解析
- while ((charData = isr2.read()) != -1) {
- System.out.print((char)charData);// 大家好
- }
- isr2.close();
- }
- }
- ```
- ## 6.4 OutputStreamWriter类
- 转换流`java.io.OutputStreamWriter` ,是Writer的子类,是从字符流到字节流的桥梁。使用指定的字符集将字符编码为字节。它的字符集可以由名称指定,也可以接受平台的默认字符集。
- - `OutputStreamWriter(OutputStream in)`: 创建一个使用默认字符集的字符流。
- - `OutputStreamWriter(OutputStream in, String charsetName)`: 创建一个指定字符集的字符流。
- 构造举例,代码如下:
- ```java
- OutputStreamWriter isr = new OutputStreamWriter(new FileOutputStream("out.txt"));
- OutputStreamWriter isr2 = new OutputStreamWriter(new FileOutputStream("out.txt") , "GBK");
- ```
- 示例代码:
- ```java
- package com.lc.transfer;
- import java.io.FileOutputStream;
- import java.io.IOException;
- import java.io.OutputStreamWriter;
- public class OutputStreamWriterDemo {
- public static void main(String[] args) throws IOException {
- // 定义文件路径
- String FileName = "E:\\out_utf8.txt";
- // 创建流对象,默认UTF8编码
- OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream(FileName));
- // 写出数据
- osw.write("你好"); // 保存为6个字节
- osw.close();
- // 定义文件路径
- String FileName2 = "E:\\out_gbk.txt";
- // 创建流对象,指定GBK编码
- OutputStreamWriter osw2 = new OutputStreamWriter(new FileOutputStream(FileName2),"GBK");
- // 写出数据
- osw2.write("你好");// 保存为4个字节
- osw2.close();
- }
- }
- ```
- ## 6.5 转换流理解图解
- **转换流是字节与字符间的桥梁!**
- 
- # 第七章 序列化 了解
- ## 7.1 概述
- Java 提供了一种对象**序列化**的机制。用一个字节序列可以表示一个对象,该字节序列包含该`对象的数据`、`对象的类型`和`对象中存储的属性`等信息。字节序列写出到文件之后,相当于文件中**持久保存**了一个对象的信息。
- 反之,该字节序列还可以从文件中读取回来,重构对象,对它进行**反序列化**。`对象的数据`、`对象的类型`和`对象中存储的数据`信息,都可以用来在内存中创建对象。
- ## 7.2 ObjectOutputStream类
- `java.io.ObjectOutputStream ` 类,将Java对象的原始数据类型写出到文件,实现对象的持久存储。
- ### 构造方法
- * `public ObjectOutputStream(OutputStream out) `: 创建一个指定OutputStream的ObjectOutputStream。
- 构造举例,代码如下:
- ```java
- FileOutputStream fileOut = new FileOutputStream("employee.txt");
- ObjectOutputStream out = new ObjectOutputStream(fileOut);
- ```
- ### 序列化操作
- 1. 一个对象要想序列化,必须满足两个条件:
- * 该类必须实现`java.io.Serializable ` 接口,`Serializable` 是一个标记接口,不实现此接口的类将不会使任何状态序列化或反序列化,会抛出`NotSerializableException` 。
- * 该类的所有属性必须是可序列化的。如果有一个属性不需要可序列化的,则该属性必须注明是瞬态的,使用`transient` 关键字修饰。
- ```java
- public class Employee implements java.io.Serializable {
- public String name;
- public String address;
- public transient int age; // transient瞬态修饰成员,不会被序列化
- public void addressCheck() {
- System.out.println("Address check : " + name + " -- " + address);
- }
- }
- ```
- 2.写出对象方法
- * `public final void writeObject (Object obj)` : 将指定的对象写出。
- ```java
- //第一步:
- //创建对象
- User u = new User("zhangsan","123");
- //第二步:
- //创建对象操作流,把整个对象写到本地文件
- ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("a.txt"));
- //第三步:
- //写出数据
- oos.writeObject(u);
- //第三步:
- //释放资源
- oos.close();
- ```
- ## 7.3 ObjectInputStream类
- ObjectInputStream反序列化流,将之前使用ObjectOutputStream序列化的原始数据恢复为对象。
- ### 构造方法
- * `public ObjectInputStream(InputStream in) `: 创建一个指定InputStream的ObjectInputStream。
- ### 反序列化操作1
- 如果能找到一个对象的class文件,我们可以进行反序列化操作,调用`ObjectInputStream`读取对象的方法:
- - `public final Object readObject ()` : 读取一个对象。
- ```java
- //读取
- ObjectInputStream ois = new ObjectInputStream(new FileInputStream("a.txt"));
- //读取数据
- User o = (User) ois.readObject();
- System.out.println(o);
- //释放资源
- ois.close();
- ```
- **对于JVM可以反序列化对象,它必须是能够找到class文件的类。如果找不到该类的class文件,则抛出一个 `ClassNotFoundException` 异常。**
- ### **反序列化操作2**
- **另外,当JVM反序列化对象时,能找到class文件,但是class文件在序列化对象之后发生了修改,那么反序列化操作也会失败,抛出一个`InvalidClassException`异常。**发生这个异常的原因如下:
- * 该类的序列版本号与从流中读取的类描述符的版本号不匹配
- * 该类包含未知数据类型
- * 该类没有可访问的无参数构造方法
- `Serializable` 接口给需要序列化的类,提供了一个序列版本号。`serialVersionUID` 该版本号的目的在于验证序列化的对象和对应类是否版本匹配。
- ```java
- public class Employee implements java.io.Serializable {
- // 加入序列版本号
- private static final long serialVersionUID = 1L;
- public String name;
- public String address;
- // 添加新的属性 ,重新编译, 可以反序列化,该属性赋为默认值.
- public int eid;
- public void addressCheck() {
- System.out.println("Address check : " + name + " -- " + address);
- }
- }
- ```
- ### 13.8.2 JDK1.7之后引入新try..catch
- 语法格式:
- ```java
- try(需要关闭的资源对象的声明){
- 业务逻辑代码
- }catch(异常类型 e){
- 处理异常代码
- }catch(异常类型 e){
- 处理异常代码
- }
- ....
- ```
- 它没有finally,也不需要程序员去关闭资源对象,无论是否发生异常,都会关闭资源对象。
- 需要指出的是,为了保证try语句可以正常关闭资源,这些资源实现类必须实现AutoCloseable或Closeable接口,实现这两个接口就必须实现close方法。Closeable是AutoCloseable的子接口。Java7几乎把所有的“资源类”(包括文件IO的各种类、JDBC编程的Connection、Statement等接口…)进行了改写,改写后资源类都是实现了AutoCloseable或Closeable接口,并实现了close方法。
- 写到try()中的资源类的变量默认是final声明的,不能修改。
- 示例代码:
- ```java
- @Test
- public void test03() {
- //从d:/1.txt(GBK)文件中,读取内容,写到项目根目录下1.txt(UTF-8)文件中
- try(
- FileInputStream fis = new FileInputStream("d:/1.txt");
- InputStreamReader isr = new InputStreamReader(fis,"GBK");
- BufferedReader br = new BufferedReader(isr);
- FileOutputStream fos = new FileOutputStream("1.txt");
- OutputStreamWriter osw = new OutputStreamWriter(fos,"UTF-8");
- BufferedWriter bw = new BufferedWriter(osw);
- ){
- String str;
- while((str = br.readLine()) != null){
- bw.write(str);
- bw.newLine();
- }
- } catch (FileNotFoundException e) {
- e.printStackTrace();
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- ```
- # 第八章 Properties属性集
- ## 8.1 概述
- `java.util.Properties ` 继承于` Hashtable` ,来表示一个持久的属性集。它使用键值结构存储数据,每个键及其对应值都是一个字符串。该类也被许多Java类使用,比如获取系统属性时,`System.getProperties` 方法就是返回一个`Properties`对象。
- ## 8.2 Properties类
- ### 构造方法
- - `public Properties()` :创建一个空的属性列表。
- ### 基本的存储方法
- * 一般下面的这些方法不用,用Map集合里面的put等方法
- - `public Object setProperty(String key, String value)` : 保存一对属性。
- - `public String getProperty(String key) ` :使用此属性列表中指定的键搜索属性值。
- - `public Set<String> stringPropertyNames() ` :所有键的名称的集合。
- ```java
- //Java 1.0 的时候,是没有集合体系的。
- //单列集合: Vector
- //双列集合:Hashtable
- //上面的类和Properties 都是1.0的时候出来的。
- //之后,发现集合挺好用的,而且在大量的场景中,都能用到集合
- //所以,在JDK1.2的时候,推出了集合体系。
- //Properties就开始使用集合体系里面的共有方法,而原来的特有方法就不用了。
- public class PropertiesDemo1 {
- public static void main(String[] args) {
- //1,Properties本身在Java中,是Map体系中的一员
- //本身也是一个双列集合
- //创建对象的时候,不用写泛型
- //不写泛型,表示可以往集合中存储任意的数据类型
- //但是我们一般不会这么干,一般只会把字符串存入。
- Properties prop = new Properties();
- //2.添加
- prop.put("zhangsan","123");
- prop.put("lisi","1234");
- prop.put("wangwu","12345");
- //3.遍历
- Set<Object> keys = prop.keySet();
- for (Object key : keys) {
- String value = prop.get(key) + "";
- System.out.println(key + ", " + value);
- }
- }
- }
- ```
- ### 与流相关的方法
- - `public void load(InputStream inStream)`: 从字节输入流中读取键值对。
- 参数中使用了字节输入流,通过流对象,可以关联到某文件上,这样就能够加载文本中的数据了。文本数据格式:
- ```properties
- filename=a.txt
- length=209385038
- location=D:\a.txt
- ```
- ### 加载代码
- ```java
- //1.创建对象
- Properties prop = new Properties();
- //2.加载
- //Properties集合的本地文件,有一个命名规则:XXX.properties
- //会把本地properties文件当中的键值对,直接读到内存中,并存入到集合里面
- //省得我们自己读取再切割了。
- //细节1:
- //如果配置文件中,有中文,那么需要用FileReader
- //细节2:
- //在实际开发中,一般来讲,我们不会在properties文件里面写中文,一般都写英文
- FileInputStream fis = new FileInputStream("day10-code\\prop.properties");
- prop.load(fis);
- //3.打印集合
- System.out.println(prop);
- //用完之后,关流
- fis.close();
- ```
- ####
- > 小贴士:文本中的数据,必须是键值对形式,不可以使用空格、等号、冒号等符号分隔。
- # 第九章 综合练习
- ## 练习1:按照层级目录拷贝文件夹
- 需求:
- 将某个磁盘的文件夹拷贝到另一个文件夹下去,包括文件夹中的全部信息
- 需要考虑子文件夹
- 代码示例:
- ```java
- public class Test1 {
- public static void main(String[] args) throws IOException {
- /*需求:将某个磁盘的文件夹拷贝到另一个文件夹下去,
- 包括文件夹中的全部信息,需要考虑子文件夹*/
- //要拷贝的文件夹:C:\Users\moon\Desktop\aaa
- //技术选型:
- //字节流:拷贝
- //字符流:读和写
- //缓冲流:提高效率
- //转换流:指定编码读写
- //对象操作流/序列化流、反序列化流:把对象写到本地,读取本地文件中的对象
- //因为本题是拷贝:所以选择字节流或缓冲流
- //因为要考虑子文件夹,所以需要用到递归
- //数据源
- File src = new File("C:\\Users\\moon\\Desktop\\aaa");
- //目的地
- File dest = new File("C:\\Users\\moon\\Desktop\\bbb");
- copyDir(src,dest);
- }
- //数据源 src
- //目的地 dest
- public static void copyDir(File src, File dest) throws IOException {
- //创建目的地文件夹
- //此时不需要判断,如果目的地文件夹存在,大不了创建失败。
- dest.mkdirs();
- File[] files = src.listFiles();
- for (File file : files) {
- if(file.isFile()){
- //如果是文件,就拷贝
- FileInputStream fis = new FileInputStream(file);//src里面的a.txt
- FileOutputStream fos = new FileOutputStream(new File(dest,file.getName()));//dest 里面的a.txt
- byte[] bytes = new byte[1024];
- int len;
- while((len = fis.read(bytes)) != -1){
- fos.write(bytes,0,len);
- }
- fos.close();
- fis.close();
- }else{
- //如果是文件夹,就递归
- //把第一个参数里面的内容,拷贝到第二个参数里面去
- //file:src --- aaa
- //目的地:dest里面的aaa
- copyDir(file, new File(dest,file.getName()));
- }
- }
- }
- }
- ```
- ## 练习2:点名器升级版
- 需求:
- 有一个文件里面存储了班级同学的姓名,每一个姓名占一行,要求通过程序实现随机点名器。
- 第三次必定是张三同学
- 核心思路:
- 1.定义一个文件存储学生的姓名
- 2.定义第二个文件记录程序运行的次数
- 3.先读取次数,如果是第三次,直接打印
- 4.如果不是第三次,则读取存储学生姓名的文件,并随机姓名
- 5.再把当前运行的次数写会文件,永久保存
- 代码示例:
- ```java
- //1.获取当前程序运行的次数
- BufferedReader br = new BufferedReader(new FileReader("day10-code\\count.txt"));
- String line = br.readLine();
- int count = Integer.parseInt(line);
- //count表示程序已经运行了多少次
- //表示程序又运行了一次
- count++;
- if (count == 3) {
- System.out.println("何江");
- } else {
- //随机
- //1.把文件中所有同学的名字都读到内存中。
- ArrayList<String> list = new ArrayList<>();
- BufferedReader br2 = new BufferedReader(new FileReader("day10-code\\studentname.txt"));
- String line2;
- while ((line2 = br2.readLine()) != null) {
- list.add(line2);
- }
- br2.close();
- //当循环结束之后,表示文件中所有同学的名字都读到集合中了
- System.out.println(list);
- Random r = new Random();
- int randomIndex = r.nextInt(list.size());
- String name1 = list.get(randomIndex);
- System.out.println(name1);
- }
- //把count再写会文件
- BufferedWriter bw = new BufferedWriter(new FileWriter("day10-code\\count.txt"));
- bw.write(count + "");
- bw.close();
- ``
|