a.txt 58 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599
  1. # 第一章 File类
  2. `java.io.File` 类是文件和目录路径名的抽象表示,主要用于文件和目录的创建、查找和删除等操作。
  3. File类是java.io包下代表与平台无关的文件和目录
  4. ## 1.1 构造方法
  5. | 构造器 | 描述 |
  6. | ----------------------------------- | ------------------------------------------------------------ |
  7. | `File(File parent, String child)` | 从父抽象路径名和子路径名字符串创建新的 `File`实例。 |
  8. | `File(String pathname)` | 通过将给定的路径名字符串转换为抽象路径名来创建新的 `File`实例。 |
  9. | `File(String parent, String child)` | 从父路径名字符串和子路径名字符串创建新的 `File`实例。 |
  10. | `File(URI uri)` | 通过将给定的 `file:` URI转换为抽象路径名来创建新的 `File`实例。 |
  11. 注意:
  12. - 一个File对象代表硬盘或网络中可能存在的一个文件或者目录。
  13. - 无论该路径下是否存在文件或者目录,都不影响File对象的创建。
  14. 示例代码如下:
  15. ```java
  16. package com.lc.file;
  17. import java.io.File;
  18. public class FileObjectTest {
  19. public static void main(String[] args) {
  20. // 文件路径名
  21. String pathname = "D:\\aaa.txt";
  22. File file1 = new File(pathname);
  23. // 文件路径名
  24. String pathname2 = "D:\\aaa\\bbb.txt";
  25. File file2 = new File(pathname2);
  26. // 通过父路径和子路径字符串
  27. String parent = "d:\\aaa";
  28. String child = "bbb.txt";
  29. File file3 = new File(parent, child);
  30. // 通过父级File对象和子路径字符串
  31. File parentDir = new File("d:\\aaa");
  32. String childFile = "bbb.txt";
  33. File file4 = new File(parentDir, childFile);
  34. }
  35. }
  36. ```
  37. ## 1.2 常用方法
  38. ### 获取判断方法
  39. | 方法 | 描述 |
  40. | ---------------------------- | ------------------------------------------------------------ |
  41. | public String getName() | 返回由此File表示的文件或目录的名称。 |
  42. | public long length() | 返回由此File表示的文件的长度。 如果此路径名表示一个目录,则返回值是不确定的。 |
  43. | public long lastModified() | 返回File对象对应的文件或目录的最后修改时间(毫秒值)。 |
  44. | public boolean exists() | 此File表示的文件或目录是否实际存在。 |
  45. | public boolean isDirectory() | 此File表示的是否为目录。 |
  46. | public boolean isFile() | 此File表示的是否为文件。 |
  47. | public boolean isHidden() | 此File表示的是否为隐藏文件或目录。 |
  48. 注意:如果File对象代表的文件或目录存在,则File对象实例初始化时,就会用硬盘中对应文件或目录的属性信息(例如,时间、类型等)为File对象的属性赋值,否则除了路径和名称,File对象的其他属性将会保留默认值。
  49. 示例代码如下:
  50. ```java
  51. ```
  52. ### 创建删除方法
  53. | 方法 | 描述 |
  54. | ---------------------------------- | -------------------------------------------------------- |
  55. | public boolean createNewFile**() | 当且仅当具有该名称的文件尚不存在时,创建一个新的空文件。 |
  56. | public boolean **delete**() | 删除由此File表示的文件或==空==目录。 |
  57. | public boolean mkdir() | 创建由此File表示的目录。 |
  58. | public boolean mkdirs() | 创建由此File表示的目录,包括任何必需但不存在的父目录。 |
  59. | public boolean renameTo(File dest) | 重新命名此抽象路径名表示的文件或目录。 |
  60. 方法演示,代码如下:
  61. ```java
  62. ```
  63. ### 文件列表
  64. | 方法 | 描述 |
  65. | ---------------------------------------------- | ------------------------------------------------------------ |
  66. | public File getParentFile() | 返回此抽象路径名父目录的抽象路径名 |
  67. | public File[] listFiles() | 返回一个File数组,所有的子文件或目录。 |
  68. | public File[] listFiles(FileFilter filter) | 返回所有满足指定过滤器的文件和目录。<br>如果给定 filter 为 null,则接受所有路径名。 |
  69. | public File[] listFiles(FilenameFilter filter) | 路径名满足过滤器返回true。 |
  70. ```java
  71. public class Test {
  72. public static void main(String[] args) {
  73. //打印一个文件夹里面所有的内容,打印所有文件的名字
  74. File file = new File("C:\\Users\\Desktop\\aaa");
  75. printFileName(file);
  76. }
  77. public static void printFileName(File src) {
  78. //1.进入文件夹
  79. //2,遍历数组
  80. //3.判断,是否为文件,如果是文件,打印名字
  81. //4.判断,是否为文件夹,如果是文件夹,递归
  82. File[] files = src.listFiles();
  83. for (File file : files) {
  84. if (file.isFile()) {
  85. System.out.println(file.getName());
  86. } else {
  87. //再次调用的时候,参数一定是src里面的子文件夹
  88. printFileName(file);
  89. }
  90. }
  91. }
  92. }
  93. ```
  94. ### 路径问题
  95. | 方法 | 描述 |
  96. | ------------------------------- | ------------------------------ |
  97. | public String getPath() | 将此File转换为路径名字符串。 |
  98. | public String getAbsolutePath() | 返回此File的绝对路径名字符串。 |
  99. File类可以使用文件路径字符串来创建File实例,该文件路径字符串既可以是绝对路径,也可以是相对路径。
  100. 默认情况下,系统总是依据用户的工作路径来解释相对路径,这个路径由系统属性“user.dir”指定,通常也就是运行Java虚拟机时所作的路径。
  101. * **构造路径**:使用File构造器创建File对象时指定的路径名。它可以是绝对路径,也可以是相对路径。
  102. * **绝对路径**:从盘符开始的路径,这是一个完整的路径。当构造路径是绝对路径时,那么getPath和getAbsolutePath结果一样。
  103. * **相对路径**:相对于**项目目录**的路径,这是一个便捷的路径,开发中经常使用。当构造路径是相对路径时,那么getAbsolutePath的路径 = user.dir的路径 + 构造路径
  104. * window的路径分隔符使用“\”,而Java程序中的“\”表示转义字符,所以在Windows中表示路径,需要用“\\”。或者直接使用“/”也可以,Java程序支持将“/”当成平台无关的路径分隔符。或者直接使用File.separator常量值表示。
  105. ```java
  106. ```
  107. # 第二章 IO概述
  108. ## 2.1 什么是IO
  109. Java中I/O操作主要是指使用`java.io`包下的内容,进行输入、输出操作。**输入**也叫做**读取**数据,**输出**也叫做作**写出**数据。File对象不能直接读取和写入数据,如果要操作数据,需要IO流。File对象好比是到水库的“路线地址”以及水库的描述信息(包括水库的大小、位置、建造时间等),要“存取”里面的水到你“家里”,需要“管道”,IO流就好比是管道。
  110. ## 2.2 IO的分类
  111. 根据数据的流向分为:**输入流**和**输出流**。
  112. - **输入流** :把数据从`其他设备`上读取到`内存`中的流。
  113. - **输出流** :把数据从`内存` 中写出到`其他设备`上的流。
  114. 格局数据的类型分为:**字节流**和**字符流**。
  115. - **字节流** :以字节为单位,读写数据的流。
  116. - **字符流** :以字符为单位,读写数据的流。
  117. ## 2.3 四大顶级抽象父类
  118. | | **输入流** | 输出流 |
  119. | :--------: | :-----------------------: | :------------------------: |
  120. | **字符流** | 字符输入流**Reader** | 字符输出流**Writer** |
  121. | **字节流** | 字节输入流**InputStream** | 字节输出流**OutputStream** |
  122. # 第三章 字节流
  123. ## 3.1 一切皆为字节
  124. 一切文件数据(文本、图片、视频等)在存储时,都是以二进制数字的形式保存,都一个一个的字节,那么传输时一样如此。所以,字节流可以传输任意文件数据。在操作流的时候,我们要时刻明确,无论使用什么样的流对象,底层传输的始终为二进制数据。
  125. ## 3.2 字节输出流【OutputStream抽象类】
  126. `java.io.OutputStream `抽象类是表示字节输出流的所有类的超类,将指定的字节信息写出到目的地。它定义了字节输出流的基本共性功能方法。
  127. - `public void close()` :关闭此输出流并释放与此流相关联的任何系统资源。
  128. - `public void flush() ` :刷新此输出流并强制任何缓冲的输出字节被写出。
  129. - `public void write(byte[] b)`:将 b.length字节从指定的字节数组写入此输出流。
  130. - `public void write(byte[] b, int off, int len)` :从指定的字节数组写入 len字节,从偏移量 off开始输出到此输出流。
  131. - `public abstract void write(int b)` :将指定的字节输出流。
  132. > 小贴士:
  133. >
  134. > close方法,当完成流的操作时,必须调用此方法,释放系统资源。
  135. ## 3.3 FileOutputStream类(实现类)
  136. `OutputStream`有很多子类,我们从最简单的一个子类开始。
  137. `java.io.FileOutputStream `类是文件输出流,用于将数据写出到文件。
  138. ### 构造方法
  139. - `public FileOutputStream(File file)`:创建文件输出流以写入由指定的 File对象表示的文件。
  140. - `public FileOutputStream(String name)`: 创建文件输出流以指定的名称写入文件。
  141. 当你创建一个流对象时,必须传入一个文件路径。该路径下,如果没有这个文件,会创建该文件。如果有这个文件,会清空这个文件的数据。
  142. - 构造举例,代码如下:
  143. ```java
  144. public class FileOutputStreamConstructor throws IOException {
  145. public static void main(String[] args) {
  146. // 使用File对象创建流对象
  147. File file = new File("a.txt");
  148. FileOutputStream fos = new FileOutputStream(file);
  149. // 使用文件名称创建流对象
  150. FileOutputStream fos = new FileOutputStream("b.txt");
  151. }
  152. }
  153. ```
  154. ### 写出字节数据
  155. 1. **写出字节**:`write(int b)` 方法,每次可以写出一个字节数据,代码使用演示:
  156. ```java
  157. public class FOSWrite {
  158. public static void main(String[] args) throws IOException {
  159. // 使用文件名称创建流对象
  160. FileOutputStream fos = new FileOutputStream("fos.txt");
  161. // 写出数据
  162. fos.write(97); // 写出第1个字节
  163. fos.write(98); // 写出第2个字节
  164. fos.write(99); // 写出第3个字节
  165. // 关闭资源
  166. fos.close();
  167. }
  168. }
  169. 输出结果:
  170. abc
  171. ```
  172. > 小贴士:
  173. >
  174. > 1. 虽然参数为int类型四个字节,但是只会保留一个字节的信息写出。
  175. > 2. 流操作完毕后,必须释放系统资源,调用close方法,千万记得。
  176. 1. **写出字节数组**:`write(byte[] b)`,每次可以写出数组中的数据,代码使用演示:
  177. ```java
  178. public class FOSWrite {
  179. public static void main(String[] args) throws IOException {
  180. // 使用文件名称创建流对象
  181. FileOutputStream fos = new FileOutputStream("fos.txt");
  182. // 字符串转换为字节数组
  183. byte[] b = "爱扣钉".getBytes();
  184. // 写出字节数组数据
  185. fos.write(b);
  186. // 关闭资源
  187. fos.close();
  188. }
  189. }
  190. 输出结果:
  191. 爱扣钉
  192. ```
  193. 1. **写出指定长度字节数组**:`write(byte[] b, int off, int len)` ,每次写出从off索引开始,len个字节,代码使用演示:
  194. ```java
  195. public class FOSWrite {
  196. public static void main(String[] args) throws IOException {
  197. // 使用文件名称创建流对象
  198. FileOutputStream fos = new FileOutputStream("fos.txt");
  199. // 字符串转换为字节数组
  200. byte[] b = "abcde".getBytes();
  201. // 写出从索引2开始,2个字节。索引2是c,两个字节,也就是cd。
  202. fos.write(b,2,2);
  203. // 关闭资源
  204. fos.close();
  205. }
  206. }
  207. 输出结果:
  208. cd
  209. ```
  210. ### 数据追加
  211. 经过以上的演示,每次程序运行,创建输出流对象,都会清空目标文件中的数据。如何保留目标文件中数据,还能继续添加新数据呢?
  212. - `public FileOutputStream(File file, boolean append)`: 创建文件输出流以写入由指定的 File对象表示的文件。
  213. - `public FileOutputStream(String name, boolean append)`: 创建文件输出流以指定的名称写入文件。
  214. 这两个构造方法,参数中都需要传入一个boolean类型的值,`true` 表示追加数据,`false` 表示清空原有数据。这样创建的输出流对象,就可以指定是否追加续写了,代码使用演示:
  215. ```java
  216. public class FOSWrite {
  217. public static void main(String[] args) throws IOException {
  218. // 使用文件名称创建流对象
  219. FileOutputStream fos = new FileOutputStream("fos.txt",true);
  220. // 字符串转换为字节数组
  221. byte[] b = "abcde".getBytes();
  222. // 写出从索引2开始,2个字节。索引2是c,两个字节,也就是cd。
  223. fos.write(b);
  224. // 关闭资源
  225. fos.close();
  226. }
  227. }
  228. 文件操作前:cd
  229. 文件操作后:cdabcde
  230. ```
  231. ## 3.4 字节输入流【InputStream】
  232. `java.io.InputStream `抽象类是表示字节输入流的所有类的超类,可以读取字节信息到内存中。它定义了字节输入流的基本共性功能方法。
  233. - `public void close()` :关闭此输入流并释放与此流相关联的任何系统资源。
  234. - `public abstract int read()`: 从输入流读取数据的下一个字节。
  235. - `public int read(byte[] b)`: 从输入流中读取一些字节数,并将它们存储到字节数组 b中 。
  236. > 小贴士:
  237. >
  238. > close方法,当完成流的操作时,必须调用此方法,释放系统资源。
  239. ## 3.5 FileInputStream类
  240. `java.io.FileInputStream `类是文件输入流,从文件中读取字节。
  241. ### 构造方法
  242. - `FileInputStream(File file)`: 通过打开与实际文件的连接来创建一个 FileInputStream ,该文件由文件系统中的 File对象 file命名。
  243. - `FileInputStream(String name)`: 通过打开与实际文件的连接来创建一个 FileInputStream ,该文件由文件系统中的路径名 name命名。
  244. 当你创建一个流对象时,必须传入一个文件路径。该路径下,如果没有该文件,会抛出`FileNotFoundException`
  245. - 构造举例,代码如下:
  246. ```java
  247. public class FileInputStreamConstructor throws IOException{
  248. public static void main(String[] args) {
  249. // 使用File对象创建流对象
  250. File file = new File("a.txt");
  251. FileInputStream fos = new FileInputStream(file);
  252. // 使用文件名称创建流对象
  253. FileInputStream fos = new FileInputStream("b.txt");
  254. }
  255. }
  256. ```
  257. ### 读取字节数据
  258. 1. **读取字节**:`read`方法,每次可以读取一个字节的数据,提升为int类型,读取到文件末尾,返回`-1`,代码使用演示:
  259. ```java
  260. public class FISRead {
  261. public static void main(String[] args) throws IOException{
  262. // 使用文件名称创建流对象
  263. FileInputStream fis = new FileInputStream("read.txt");
  264. // 读取数据,返回一个字节
  265. int read = fis.read();
  266. System.out.println((char) read);
  267. read = fis.read();
  268. System.out.println((char) read);
  269. read = fis.read();
  270. System.out.println((char) read);
  271. read = fis.read();
  272. System.out.println((char) read);
  273. read = fis.read();
  274. System.out.println((char) read);
  275. // 读取到末尾,返回-1
  276. read = fis.read();
  277. System.out.println( read);
  278. // 关闭资源
  279. fis.close();
  280. }
  281. }
  282. 输出结果:
  283. a
  284. b
  285. c
  286. d
  287. e
  288. -1
  289. ```
  290. 循环改进读取方式,代码使用演示:
  291. ```java
  292. public class FISRead {
  293. public static void main(String[] args) throws IOException{
  294. // 使用文件名称创建流对象
  295. FileInputStream fis = new FileInputStream("read.txt");
  296. // 定义变量,保存数据
  297. int b ;
  298. // 循环读取
  299. while ((b = fis.read())!=-1) {
  300. System.out.println((char)b);
  301. }
  302. // 关闭资源
  303. fis.close();
  304. }
  305. }
  306. 输出结果:
  307. a
  308. b
  309. c
  310. d
  311. e
  312. ```
  313. > 小贴士:
  314. >
  315. > 1. 虽然读取了一个字节,但是会自动提升为int类型。
  316. > 2. 流操作完毕后,必须释放系统资源,调用close方法,千万记得。
  317. 1. **使用字节数组读取**:`read(byte[] b)`,每次读取b的长度个字节到数组中,返回读取到的有效字节个数,读取到末尾时,返回`-1` ,代码使用演示:
  318. ```java
  319. public class FISRead {
  320. public static void main(String[] args) throws IOException{
  321. // 使用文件名称创建流对象.
  322. FileInputStream fis = new FileInputStream("read.txt"); // 文件中为abcde
  323. // 定义变量,作为有效个数
  324. int len ;
  325. // 定义字节数组,作为装字节数据的容器
  326. byte[] b = new byte[2];
  327. // 循环读取
  328. while (( len= fis.read(b))!=-1) {
  329. // 每次读取后,把数组变成字符串打印
  330. System.out.println(new String(b));
  331. }
  332. // 关闭资源
  333. fis.close();
  334. }
  335. }
  336. 输出结果:
  337. ab
  338. cd
  339. ed
  340. ```
  341. 错误数据`d`,是由于最后一次读取时,只读取一个字节`e`,数组中,上次读取的数据没有被完全替换,所以要通过`len` ,获取有效的字节,代码使用演示:
  342. ```java
  343. public class FISRead {
  344. public static void main(String[] args) throws IOException{
  345. // 使用文件名称创建流对象.
  346. FileInputStream fis = new FileInputStream("read.txt"); // 文件中为abcde
  347. // 定义变量,作为有效个数
  348. int len ;
  349. // 定义字节数组,作为装字节数据的容器
  350. byte[] b = new byte[2];
  351. // 循环读取
  352. while (( len= fis.read(b))!=-1) {
  353. // 每次读取后,把数组的有效字节部分,变成字符串打印
  354. System.out.println(new String(b,0,len));// len 每次读取的有效字节个数
  355. }
  356. // 关闭资源
  357. fis.close();
  358. }
  359. }
  360. 输出结果:
  361. ab
  362. cd
  363. e
  364. ```
  365. > 小贴士:
  366. >
  367. > 使用数组读取,每次读取多个字节,减少了系统间的IO操作次数,从而提高了读写的效率,建议开发中使用。
  368. ## 3.6 复制文件
  369. 一切文件数据(文本、图片、视频等)在存储时,都是以二进制数字的形式保存,都一个一个的字节,那么传输时一样如此。所以,字节流可以传输任意文件数据。在操作流的时候,我们要时刻明确,无论使用什么样的流对象,底层传输的始终为二进制数据。
  370. ![](imgs/2_copy.jpg)
  371. 复制图片文件,代码使用演示:
  372. ```java
  373. package com.lc.fileio;
  374. import java.io.FileInputStream;
  375. import java.io.FileOutputStream;
  376. import java.io.IOException;
  377. public class FileCopy {
  378. public static void main(String[] args) throws IOException {
  379. // 1.创建流对象
  380. // 1.1 指定数据源
  381. FileInputStream fis = new FileInputStream("D:\\test.jpg");
  382. // 1.2 指定目的地
  383. FileOutputStream fos = new FileOutputStream("test_copy.jpg");
  384. // 2.读写数据
  385. // 2.1 定义数组
  386. byte[] b = new byte[1024];
  387. // 2.2 定义长度
  388. int len;
  389. // 2.3 循环读取
  390. while ((len = fis.read(b))!=-1) {
  391. // 2.4 写出数据
  392. fos.write(b, 0 , len);
  393. }
  394. // 3.关闭资源
  395. fos.close();
  396. fis.close();
  397. }
  398. }
  399. ```
  400. # 第四章 字符流
  401. 当使用字节流读取文本文件时,可能会有一个小问题。就是遇到中文字符时,可能不会显示完整的字符,那是因为一个中文字符可能占用多个字节存储。所以Java提供一些字符流类,以字符为单位读写数据,专门用于处理文本文件。
  402. ## 4.1 字符输入流【Reader】
  403. `java.io.Reader`抽象类是表示用于读取字符流的所有类的超类,可以读取字符信息到内存中。它定义了字符输入流的基本共性功能方法。
  404. - `public void close()` :关闭此流并释放与此流相关联的任何系统资源。
  405. - `public int read()`: 从输入流读取一个字符。
  406. - `public int read(char[] cbuf)`: 从输入流中读取一些字符,并将它们存储到字符数组 cbuf中 。
  407. ## 4.2 FileReader类
  408. `java.io.FileReader `类是读取字符文件的便利类。构造时使用系统默认的字符编码。
  409. > 小贴士:
  410. >
  411. > 1. 字符编码:字节与字符的对应规则。Windows系统的中文编码默认是GBK编码表。
  412. >
  413. > idea中UTF-8
  414. ### 构造方法
  415. - `FileReader(File file)`: 创建一个新的 FileReader ,给定要读取的File对象。
  416. - `FileReader(String fileName)`: 创建一个新的 FileReader ,给定要读取的文件的名称。
  417. 当你创建一个流对象时,必须传入一个文件路径。类似于FileInputStream 。
  418. - 构造举例,代码如下:
  419. ```java
  420. public class FileReaderConstructor throws IOException{
  421. public static void main(String[] args) {
  422. // 使用File对象创建流对象
  423. File file = new File("a.txt");
  424. FileReader fr = new FileReader(file);
  425. // 使用文件名称创建流对象
  426. FileReader fr = new FileReader("b.txt");
  427. }
  428. }
  429. ```
  430. ### 读取字符数据
  431. 1. **读取字符**:`read`方法,每次可以读取一个字符的数据,提升为int类型,读取到文件末尾,返回`-1`,循环读取,代码使用演示:
  432. ```java
  433. public class FRRead {
  434. public static void main(String[] args) throws IOException {
  435. // 使用文件名称创建流对象
  436. FileReader fr = new FileReader("read.txt");
  437. // 定义变量,保存数据
  438. int b ;
  439. // 循环读取
  440. while ((b = fr.read())!=-1) {
  441. System.out.println((char)b);
  442. }
  443. // 关闭资源
  444. fr.close();
  445. }
  446. }
  447. 输出结果:
  448. ```
  449. > 小贴士:虽然读取了一个字符,但是会自动提升为int类型。
  450. 1. **使用字符数组读取**:`read(char[] cbuf)`,每次读取b的长度个字符到数组中,返回读取到的有效字符个数,读取到末尾时,返回`-1` ,代码使用演示:
  451. ```java
  452. public class FRRead {
  453. public static void main(String[] args) throws IOException {
  454. // 使用文件名称创建流对象
  455. FileReader fr = new FileReader("read.txt");
  456. // 定义变量,保存有效字符个数
  457. int len ;
  458. // 定义字符数组,作为装字符数据的容器
  459. char[] cbuf = new char[2];
  460. // 循环读取
  461. while ((len = fr.read(cbuf))!=-1) {
  462. System.out.println(new String(cbuf));
  463. }
  464. // 关闭资源
  465. fr.close();
  466. }
  467. }
  468. 输出结果:
  469. 黑马
  470. 程序
  471. 员序
  472. ```
  473. 获取有效的字符改进,代码使用演示:
  474. ```java
  475. public class FISRead {
  476. public static void main(String[] args) throws IOException {
  477. // 使用文件名称创建流对象
  478. FileReader fr = new FileReader("read.txt");
  479. // 定义变量,保存有效字符个数
  480. int len ;
  481. // 定义字符数组,作为装字符数据的容器
  482. char[] cbuf = new char[2];
  483. // 循环读取
  484. while ((len = fr.read(cbuf))!=-1) {
  485. System.out.println(new String(cbuf,0,len));
  486. }
  487. // 关闭资源
  488. fr.close();
  489. }
  490. }
  491. 输出结果:
  492. 黑马
  493. 程序
  494. ```
  495. ## 4.3 字符输出流【Writer】
  496. `java.io.Writer `抽象类是表示用于写出字符流的所有类的超类,将指定的字符信息写出到目的地。它定义了字节输出流的基本共性功能方法。
  497. - `public abstract void close()` :关闭此输出流并释放与此流相关联的任何系统资源。
  498. - `public abstract void flush() ` :刷新此输出流并强制任何缓冲的输出字符被写出。
  499. - `public void write(int c)` :写出一个字符。
  500. - `public void write(char[] cbuf)`:将 b.length字符从指定的字符数组写出此输出流。
  501. - `public abstract void write(char[] b, int off, int len)` :从指定的字符数组写出 len字符,从偏移量 off开始输出到此输出流。
  502. - `public void write(String str)` :写出一个字符串。
  503. ## 4.4 FileWriter类
  504. `java.io.FileWriter `类是写出字符到文件的便利类。构造时使用系统默认的字符编码。
  505. ### 构造方法
  506. - `FileWriter(File file)`: 创建一个新的 FileWriter,给定要读取的File对象。
  507. - `FileWriter(String fileName)`: 创建一个新的 FileWriter,给定要读取的文件的名称。
  508. 当你创建一个流对象时,必须传入一个文件路径,类似于FileOutputStream。
  509. - 构造举例,代码如下:
  510. ```java
  511. public class FileWriterConstructor {
  512. public static void main(String[] args) throws IOException {
  513. // 使用File对象创建流对象
  514. File file = new File("a.txt");
  515. FileWriter fw = new FileWriter(file);
  516. // 使用文件名称创建流对象
  517. FileWriter fw = new FileWriter("b.txt");
  518. }
  519. }
  520. ```
  521. ### 基本写出数据
  522. **写出字符**:`write(int b)` 方法,每次可以写出一个字符数据,代码使用演示:
  523. ```java
  524. public class FWWrite {
  525. public static void main(String[] args) throws IOException {
  526. // 使用文件名称创建流对象
  527. FileWriter fw = new FileWriter("fw.txt");
  528. // 写出数据
  529. fw.write(97); // 写出第1个字符
  530. fw.write('b'); // 写出第2个字符
  531. fw.write('C'); // 写出第3个字符
  532. fw.write(30000); // 写出第4个字符,中文编码表中30000对应一个汉字。
  533. /*
  534. 【注意】流最后都要释放资源
  535. */
  536. fw.close();
  537. }
  538. }
  539. 输出结果:
  540. abC田
  541. ```
  542. > 小贴士:
  543. >
  544. > 1. 虽然参数为int类型四个字节,但是只会保留一个字符的信息写出。
  545. ### 写出其他数据
  546. 1. **写出字符数组** :`write(char[] cbuf)` 和 `write(char[] cbuf, int off, int len)` ,每次可以写出字符数组中的数据,用法类似FileOutputStream,代码使用演示:
  547. ```java
  548. public class FWWrite {
  549. public static void main(String[] args) throws IOException {
  550. // 使用文件名称创建流对象
  551. FileWriter fw = new FileWriter("fw.txt");
  552. // 字符串转换为字节数组
  553. char[] chars = "黑马程序员".toCharArray();
  554. // 写出字符数组
  555. fw.write(chars); // 黑马程序员
  556. // 写出从索引2开始,2个字节。索引2是'程',两个字节,也就是'程序'。
  557. fw.write(b,2,2); // 程序
  558. // 关闭资源
  559. fos.close();
  560. }
  561. }
  562. ```
  563. 1. **写出字符串**:`write(String str)` 和 `write(String str, int off, int len)` ,每次可以写出字符串中的数据,更为方便,代码使用演示:
  564. ```java
  565. public class FWWrite {
  566. public static void main(String[] args) throws IOException {
  567. // 使用文件名称创建流对象
  568. FileWriter fw = new FileWriter("fw.txt");
  569. // 字符串
  570. String msg = "黑马程序员";
  571. // 写出字符数组
  572. fw.write(msg); //黑马程序员
  573. // 写出从索引2开始,2个字节。索引2是'程',两个字节,也就是'程序'。
  574. fw.write(msg,2,2); // 程序
  575. // 关闭资源
  576. fos.close();
  577. }
  578. }
  579. ```
  580. 1. **续写和换行**:操作类似于FileOutputStream。
  581. ```java
  582. public class FWWrite {
  583. public static void main(String[] args) throws IOException {
  584. // 使用文件名称创建流对象,可以续写数据
  585. FileWriter fw = new FileWriter("fw.txt",true);
  586. // 写出字符串
  587. fw.write("黑马");
  588. // 写出换行
  589. fw.write("\r\n");
  590. // 写出字符串
  591. fw.write("程序员");
  592. // 关闭资源
  593. fw.close();
  594. }
  595. }
  596. 输出结果:
  597. 黑马
  598. 程序员
  599. ```
  600. > 小贴士:字符流,只能操作文本文件,不能操作图片,视频等非文本文件。
  601. >
  602. > 当我们单纯读或者写文本文件时 使用字符流 其他情况使用字节流
  603. ## 4.5练习:键盘录入数据并写到文件
  604. 需求:
  605. ​ 从控制台循环接收用户录入的学生信息,
  606. ​ 输入格式为:学号-学生名字
  607. ​ 将学生信息保存到C盘下面的stu.txt文件中,
  608. ​ 一个学生信息占据一行数据。
  609. ​ 当用户输入end时停止输入。
  610. 代码示例:
  611. ```java
  612. //如果使用字节流不符合我们使用的规范
  613. //字节流:只做拷贝
  614. //字符流:做纯文本文件的读 和 写
  615. FileWriter fw = new FileWriter("day09-code\\a.txt");
  616. Scanner sc = new Scanner(System.in);
  617. while (true) {
  618. System.out.println("请输入学生信息");
  619. String str = sc.nextLine();
  620. if("end".equals(str)){
  621. break;
  622. }
  623. fw.write(str);
  624. fw.write("\r\n");
  625. }
  626. fw.close();
  627. ```
  628. # 第五章 缓冲流
  629. 缓冲流,也叫高效流,按照数据类型分类:
  630. * **字节缓冲流**:`BufferedInputStream`,`BufferedOutputStream`
  631. * **字符缓冲流**:`BufferedReader`,`BufferedWriter`
  632. 缓冲流的基本原理,是在创建流对象时,会创建一个内置的默认大小的缓冲区数组,通过缓冲区读写,减少系统IO次数,从而提高读写的效率。
  633. ## 5.1 构造方法
  634. * `public BufferedInputStream(InputStream in)` :创建一个 新的缓冲输入流。
  635. * `public BufferedOutputStream(OutputStream out)`: 创建一个新的缓冲输出流。
  636. 构造举例,代码如下:
  637. ```java
  638. // 创建字节缓冲输入流
  639. BufferedInputStream bis = new BufferedInputStream(new FileInputStream("bis.txt"));
  640. // 创建字节缓冲输出流
  641. BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("bos.txt"));
  642. ```
  643. * `public BufferedReader(Reader in)` :创建一个 新的缓冲输入流。
  644. * `public BufferedWriter(Writer out)`: 创建一个新的缓冲输出流。
  645. 构造举例,代码如下:
  646. ```java
  647. // 创建字符缓冲输入流
  648. BufferedReader br = new BufferedReader(new FileReader("br.txt"));
  649. // 创建字符缓冲输出流
  650. BufferedWriter bw = new BufferedWriter(new FileWriter("bw.txt"));
  651. ```
  652. ## 5.2 效率测试
  653. 查询API,缓冲流读写方法与基本的流是一致的,我们通过复制大文件(375MB),测试它的效率。
  654. ```java
  655. package com.lc.buffer;
  656. import org.junit.Test;
  657. import java.io.*;
  658. public class BufferedIO {
  659. @Test
  660. public void testNoBuffer() throws IOException {
  661. // 记录开始时间
  662. long start = System.currentTimeMillis();
  663. // 创建流对象
  664. FileInputStream fis = new FileInputStream("jdk8.exe");
  665. FileOutputStream fos = new FileOutputStream("copy.exe");
  666. // 读写数据
  667. byte[] data = new byte[1024];
  668. int len;
  669. while ((len = fis.read(data)) != -1) {
  670. fos.write(data,0,len);
  671. }
  672. fos.close();
  673. fis.close();
  674. // 记录结束时间
  675. long end = System.currentTimeMillis();
  676. System.out.println("普通流复制时间:"+(end - start)+" 毫秒");
  677. }
  678. @Test
  679. public void testUseBuffer() throws IOException {
  680. // 记录开始时间
  681. long start = System.currentTimeMillis();
  682. // 创建流对象
  683. BufferedInputStream bis = new BufferedInputStream(new FileInputStream("jdk8.exe"));
  684. BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("copy.exe"));
  685. // 读写数据
  686. int len;
  687. byte[] data = new byte[1024];
  688. while ((len = bis.read(data)) != -1) {
  689. bos.write(data, 0 , len);
  690. }
  691. bos.close();
  692. bis.close();
  693. // 记录结束时间
  694. long end = System.currentTimeMillis();
  695. System.out.println("缓冲流使用数组复制时间:"+(end - start)+" 毫秒");
  696. }
  697. }
  698. ```
  699. ## 5.3 字符缓冲流特有方法
  700. 字符缓冲流的基本方法与普通字符流调用方式一致,不再阐述,我们来看它们具备的特有方法。
  701. * BufferedReader:`public String readLine()`: 读一行文字。
  702. * BufferedWriter:`public void newLine()`: 写一行行分隔符,由系统属性定义符号。
  703. ```java
  704. package com.lc.buffer;
  705. import org.junit.Test;
  706. import java.io.*;
  707. public class BufferedIOLine {
  708. @Test
  709. public void testReadLine()throws IOException {
  710. // 创建流对象
  711. BufferedReader br = new BufferedReader(new FileReader("in.txt"));
  712. // 定义字符串,保存读取的一行文字
  713. String line;
  714. // 循环读取,读取到最后返回null
  715. while ((line = br.readLine())!=null) {
  716. System.out.println(line);
  717. }
  718. // 释放资源
  719. br.close();
  720. }
  721. @Test
  722. public void testNewLine()throws IOException{
  723. // 创建流对象
  724. BufferedWriter bw = new BufferedWriter(new FileWriter("out.txt"));
  725. // 写出数据
  726. bw.write("尚");
  727. // 写出换行
  728. bw.newLine();
  729. bw.write("硅");
  730. bw.newLine();
  731. bw.write("谷");
  732. bw.newLine();
  733. // 释放资源
  734. bw.close();
  735. }
  736. }
  737. ```
  738. ## 5.4 流的关闭顺序
  739. ```java
  740. package com.lc.buffer;
  741. import org.junit.Test;
  742. import java.io.BufferedWriter;
  743. import java.io.FileWriter;
  744. import java.io.IOException;
  745. public class IOClose {
  746. @Test
  747. public void test01() throws IOException {
  748. FileWriter fw = new FileWriter("d:/1.txt");
  749. BufferedWriter bw = new BufferedWriter(fw);
  750. bw.write("hello");
  751. fw.close();
  752. bw.close();//java.io.IOException: Stream closed
  753. /*
  754. 先写到bw(缓冲区)=>fw =>"文件"
  755. 先把fw关闭了,bw的数据无法输出了
  756. 1221 的顺序
  757. */
  758. }
  759. }
  760. ```
  761. ## 练习:文本排序
  762. 请将文本信息恢复顺序。
  763. ```
  764. 3.侍中、侍郎郭攸之、费祎、董允等,此皆良实,志虑忠纯,是以先帝简拔以遗陛下。愚以为宫中之事,事无大小,悉以咨之,然后施行,必得裨补阙漏,有所广益。
  765. 8.愿陛下托臣以讨贼兴复之效,不效,则治臣之罪,以告先帝之灵。若无兴德之言,则责攸之、祎、允等之慢,以彰其咎;陛下亦宜自谋,以咨诹善道,察纳雅言,深追先帝遗诏,臣不胜受恩感激。
  766. 4.将军向宠,性行淑均,晓畅军事,试用之于昔日,先帝称之曰能,是以众议举宠为督。愚以为营中之事,悉以咨之,必能使行阵和睦,优劣得所。
  767. 2.宫中府中,俱为一体,陟罚臧否,不宜异同。若有作奸犯科及为忠善者,宜付有司论其刑赏,以昭陛下平明之理,不宜偏私,使内外异法也。
  768. 1.先帝创业未半而中道崩殂,今天下三分,益州疲弊,此诚危急存亡之秋也。然侍卫之臣不懈于内,忠志之士忘身于外者,盖追先帝之殊遇,欲报之于陛下也。诚宜开张圣听,以光先帝遗德,恢弘志士之气,不宜妄自菲薄,引喻失义,以塞忠谏之路也。
  769. 9.今当远离,临表涕零,不知所言。
  770. 6.臣本布衣,躬耕于南阳,苟全性命于乱世,不求闻达于诸侯。先帝不以臣卑鄙,猥自枉屈,三顾臣于草庐之中,咨臣以当世之事,由是感激,遂许先帝以驱驰。后值倾覆,受任于败军之际,奉命于危难之间,尔来二十有一年矣。
  771. 7.先帝知臣谨慎,故临崩寄臣以大事也。受命以来,夙夜忧叹,恐付托不效,以伤先帝之明,故五月渡泸,深入不毛。今南方已定,兵甲已足,当奖率三军,北定中原,庶竭驽钝,攘除奸凶,兴复汉室,还于旧都。此臣所以报先帝而忠陛下之职分也。至于斟酌损益,进尽忠言,则攸之、祎、允之任也。
  772. 5.亲贤臣,远小人,此先汉所以兴隆也;亲小人,远贤臣,此后汉所以倾颓也。先帝在时,每与臣论此事,未尝不叹息痛恨于桓、灵也。侍中、尚书、长史、参军,此悉贞良死节之臣,愿陛下亲之信之,则汉室之隆,可计日而待也。
  773. ```
  774. 实现步骤
  775. 1. 逐行读取文本信息。
  776. 2. 解析文本信息到集合中。
  777. 3. 遍历集合,按顺序,写出文本信息。
  778. ```java
  779. public class Test07 {
  780. public static void main(String[] args) throws IOException {
  781. //1.定义一个TreeMap 键:序号 值:内容
  782. //默认是按照键来排序的
  783. //Integer默认的排序规则:升序
  784. TreeMap<Integer, String> tm = new TreeMap<>();
  785. //2.把所有的数据读到内存中
  786. BufferedReader br = new BufferedReader(new FileReader("a.txt"));
  787. //3.循环读取,并存入集合
  788. //细节:readLine在读取的时候,遇到回车换行符就停止了。
  789. //但是不会读回车换行
  790. String line;
  791. while ((line = br.readLine()) != null) {
  792. String[] info = line.split("\\.");
  793. int key = Integer.parseInt(info[0]);
  794. String value = info[1];
  795. tm.put(key, value);
  796. }
  797. //4.释放资源
  798. //什么时候不用了,随手就释放掉
  799. br.close();
  800. //5.遍历集合,把数据写到新的文件中
  801. BufferedWriter bw = new BufferedWriter(new FileWriter("result.txt"));
  802. Set<Integer> keys = tm.keySet();
  803. for (int key : keys) {
  804. String value = tm.get(key);
  805. bw.write(key + "." + value);
  806. bw.newLine();
  807. //写一行就刷新一下
  808. bw.flush();
  809. }
  810. //6.释放资源
  811. bw.close();
  812. }
  813. }
  814. ```
  815. # 第六章 转换流
  816. ## 6.1 字符编码和字符集
  817. ### 1、编码与解码
  818. 计算机中储存的信息都是用二进制数表示的,而我们在屏幕上看到的数字、英文、标点符号、汉字等字符是二进制数转换之后的结果。按照某种规则,将字符存储到计算机中,称为**编码** 。反之,将存储在计算机中的二进制数按照某种规则解析显示出来,称为**解码** 。比如说,按照A规则存储,同样按照A规则解析,那么就能显示正确的文本符号。反之,按照A规则存储,再按照B规则解析,就会导致乱码现象。
  819. * **字符编码`Character Encoding`** : 就是一套自然语言的字符与二进制数之间的对应规则。
  820. * **编码表**:生活中文字和计算机中二进制的对应规则
  821. ### 2、字符编码与字符集
  822. * **字符集 `Charset`**:也叫编码表。是一个系统支持的所有字符的集合,包括各国家文字、标点符号、图形符号、数字等。
  823. 计算机要准确的存储和识别各种字符集符号,需要进行字符编码,一套字符集必然至少有一套字符编码。常见字符集有ASCII字符集、GBK字符集、Unicode字符集等。
  824. * **Unicode字符集** :
  825. ![image-20240116083105299](imgs/image-20240116083105299.png)
  826. * Unicode编码系统为表达任意语言的任意字符而设计,是业界的一种标准,也称为统一码、标准万国码。
  827. * 它最多使用4个字节的数字来表达每个字母、符号,或者文字。有三种编码方案,UTF-8、UTF-16和UTF-32。最为常用的UTF-8编码。
  828. * UTF-8编码,可以用来表示Unicode标准中任何字符,它是电子邮件、网页及其他存储或传送文字的应用中,优先采用的编码。互联网工程工作小组(IETF)要求所有互联网协议都必须支持UTF-8编码。所以,我们开发Web应用,也要使用UTF-8编码。它使用一至四个字节为每个字符编码,编码规则:
  829. 1. 128个US-ASCII字符,只需一个字节编码。
  830. 2. 拉丁文等字符,需要二个字节编码。
  831. 3. 大部分常用字(含中文),使用三个字节编码。
  832. 4. 其他极少使用的Unicode辅助字符,使用四字节编码。
  833. ## 6.2 编码引出的问题
  834. 使用`FileReader` 读取项目中的文本文件。由于项目设置了UTF-8编码,当读取Windows系统中创建的文本文件时,由于Windows系统的默认是GBK编码,就会出现乱码。
  835. ```java
  836. package com.lc.transfer;
  837. import java.io.FileReader;
  838. import java.io.IOException;
  839. public class Problem {
  840. public static void main(String[] args) throws IOException {
  841. FileReader fileReader = new FileReader("E:\\File_GBK.txt");
  842. int read;
  843. while ((read = fileReader.read()) != -1) {
  844. System.out.print((char)read);
  845. }
  846. fileReader.close();
  847. }
  848. }
  849. 输出结果:
  850. ���
  851. ```
  852. 那么如何读取GBK编码的文件呢?
  853. ## 6.3 InputStreamReader类
  854. 转换流`java.io.InputStreamReader`,是Reader的子类,是从字节流到字符流的桥梁。它读取字节,并使用指定的字符集将其解码为字符。它的字符集可以由名称指定,也可以接受平台的默认字符集。
  855. * `InputStreamReader(InputStream in)`: 创建一个使用默认字符集的字符流。
  856. * `InputStreamReader(InputStream in, String charsetName)`: 创建一个指定字符集的字符流。
  857. 构造举例,代码如下:
  858. ```java
  859. InputStreamReader isr = new InputStreamReader(new FileInputStream("in.txt"));
  860. InputStreamReader isr2 = new InputStreamReader(new FileInputStream("in.txt") , "GBK");
  861. ```
  862. 示例代码:
  863. ```java
  864. package com.lc.transfer;
  865. import java.io.FileInputStream;
  866. import java.io.IOException;
  867. import java.io.InputStreamReader;
  868. public class InputStreamReaderDemo {
  869. public static void main(String[] args) throws IOException {
  870. // 定义文件路径,文件为gbk编码
  871. String fileName = "E:\\file_gbk.txt";
  872. // 创建流对象,默认UTF8编码
  873. InputStreamReader isr1 = new InputStreamReader(new FileInputStream(fileName));
  874. // 定义变量,保存字符
  875. int charData;
  876. // 使用默认编码字符流读取,乱码
  877. while ((charData = isr1.read()) != -1) {
  878. System.out.print((char)charData); // ��Һ�
  879. }
  880. isr1.close();
  881. // 创建流对象,指定GBK编码
  882. InputStreamReader isr2 = new InputStreamReader(new FileInputStream(fileName) , "GBK");
  883. // 使用指定编码字符流读取,正常解析
  884. while ((charData = isr2.read()) != -1) {
  885. System.out.print((char)charData);// 大家好
  886. }
  887. isr2.close();
  888. }
  889. }
  890. ```
  891. ## 6.4 OutputStreamWriter类
  892. 转换流`java.io.OutputStreamWriter` ,是Writer的子类,是从字符流到字节流的桥梁。使用指定的字符集将字符编码为字节。它的字符集可以由名称指定,也可以接受平台的默认字符集。
  893. - `OutputStreamWriter(OutputStream in)`: 创建一个使用默认字符集的字符流。
  894. - `OutputStreamWriter(OutputStream in, String charsetName)`: 创建一个指定字符集的字符流。
  895. 构造举例,代码如下:
  896. ```java
  897. OutputStreamWriter isr = new OutputStreamWriter(new FileOutputStream("out.txt"));
  898. OutputStreamWriter isr2 = new OutputStreamWriter(new FileOutputStream("out.txt") , "GBK");
  899. ```
  900. 示例代码:
  901. ```java
  902. package com.lc.transfer;
  903. import java.io.FileOutputStream;
  904. import java.io.IOException;
  905. import java.io.OutputStreamWriter;
  906. public class OutputStreamWriterDemo {
  907. public static void main(String[] args) throws IOException {
  908. // 定义文件路径
  909. String FileName = "E:\\out_utf8.txt";
  910. // 创建流对象,默认UTF8编码
  911. OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream(FileName));
  912. // 写出数据
  913. osw.write("你好"); // 保存为6个字节
  914. osw.close();
  915. // 定义文件路径
  916. String FileName2 = "E:\\out_gbk.txt";
  917. // 创建流对象,指定GBK编码
  918. OutputStreamWriter osw2 = new OutputStreamWriter(new FileOutputStream(FileName2),"GBK");
  919. // 写出数据
  920. osw2.write("你好");// 保存为4个字节
  921. osw2.close();
  922. }
  923. }
  924. ```
  925. ## 6.5 转换流理解图解
  926. **转换流是字节与字符间的桥梁!**
  927. ![image-20240116082704476](imgs/image-20240116082704476.png)
  928. # 第七章 序列化 了解
  929. ## 7.1 概述
  930. Java 提供了一种对象**序列化**的机制。用一个字节序列可以表示一个对象,该字节序列包含该`对象的数据`、`对象的类型`和`对象中存储的属性`等信息。字节序列写出到文件之后,相当于文件中**持久保存**了一个对象的信息。
  931. 反之,该字节序列还可以从文件中读取回来,重构对象,对它进行**反序列化**。`对象的数据`、`对象的类型`和`对象中存储的数据`信息,都可以用来在内存中创建对象。
  932. ## 7.2 ObjectOutputStream类
  933. `java.io.ObjectOutputStream ` 类,将Java对象的原始数据类型写出到文件,实现对象的持久存储。
  934. ### 构造方法
  935. * `public ObjectOutputStream(OutputStream out) `: 创建一个指定OutputStream的ObjectOutputStream。
  936. 构造举例,代码如下:
  937. ```java
  938. FileOutputStream fileOut = new FileOutputStream("employee.txt");
  939. ObjectOutputStream out = new ObjectOutputStream(fileOut);
  940. ```
  941. ### 序列化操作
  942. 1. 一个对象要想序列化,必须满足两个条件:
  943. * 该类必须实现`java.io.Serializable ` 接口,`Serializable` 是一个标记接口,不实现此接口的类将不会使任何状态序列化或反序列化,会抛出`NotSerializableException` 。
  944. * 该类的所有属性必须是可序列化的。如果有一个属性不需要可序列化的,则该属性必须注明是瞬态的,使用`transient` 关键字修饰。
  945. ```java
  946. public class Employee implements java.io.Serializable {
  947. public String name;
  948. public String address;
  949. public transient int age; // transient瞬态修饰成员,不会被序列化
  950. public void addressCheck() {
  951. System.out.println("Address check : " + name + " -- " + address);
  952. }
  953. }
  954. ```
  955. 2.写出对象方法
  956. * `public final void writeObject (Object obj)` : 将指定的对象写出。
  957. ```java
  958. //第一步:
  959. //创建对象
  960. User u = new User("zhangsan","123");
  961. //第二步:
  962. //创建对象操作流,把整个对象写到本地文件
  963. ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("a.txt"));
  964. //第三步:
  965. //写出数据
  966. oos.writeObject(u);
  967. //第三步:
  968. //释放资源
  969. oos.close();
  970. ```
  971. ## 7.3 ObjectInputStream类
  972. ObjectInputStream反序列化流,将之前使用ObjectOutputStream序列化的原始数据恢复为对象。
  973. ### 构造方法
  974. * `public ObjectInputStream(InputStream in) `: 创建一个指定InputStream的ObjectInputStream。
  975. ### 反序列化操作1
  976. 如果能找到一个对象的class文件,我们可以进行反序列化操作,调用`ObjectInputStream`读取对象的方法:
  977. - `public final Object readObject ()` : 读取一个对象。
  978. ```java
  979. //读取
  980. ObjectInputStream ois = new ObjectInputStream(new FileInputStream("a.txt"));
  981. //读取数据
  982. User o = (User) ois.readObject();
  983. System.out.println(o);
  984. //释放资源
  985. ois.close();
  986. ```
  987. **对于JVM可以反序列化对象,它必须是能够找到class文件的类。如果找不到该类的class文件,则抛出一个 `ClassNotFoundException` 异常。**
  988. ### **反序列化操作2**
  989. **另外,当JVM反序列化对象时,能找到class文件,但是class文件在序列化对象之后发生了修改,那么反序列化操作也会失败,抛出一个`InvalidClassException`异常。**发生这个异常的原因如下:
  990. * 该类的序列版本号与从流中读取的类描述符的版本号不匹配
  991. * 该类包含未知数据类型
  992. * 该类没有可访问的无参数构造方法
  993. `Serializable` 接口给需要序列化的类,提供了一个序列版本号。`serialVersionUID` 该版本号的目的在于验证序列化的对象和对应类是否版本匹配。
  994. ```java
  995. public class Employee implements java.io.Serializable {
  996. // 加入序列版本号
  997. private static final long serialVersionUID = 1L;
  998. public String name;
  999. public String address;
  1000. // 添加新的属性 ,重新编译, 可以反序列化,该属性赋为默认值.
  1001. public int eid;
  1002. public void addressCheck() {
  1003. System.out.println("Address check : " + name + " -- " + address);
  1004. }
  1005. }
  1006. ```
  1007. ### 13.8.2 JDK1.7之后引入新try..catch
  1008. 语法格式:
  1009. ```java
  1010. try(需要关闭的资源对象的声明){
  1011. 业务逻辑代码
  1012. }catch(异常类型 e){
  1013. 处理异常代码
  1014. }catch(异常类型 e){
  1015. 处理异常代码
  1016. }
  1017. ....
  1018. ```
  1019. 它没有finally,也不需要程序员去关闭资源对象,无论是否发生异常,都会关闭资源对象。
  1020. 需要指出的是,为了保证try语句可以正常关闭资源,这些资源实现类必须实现AutoCloseable或Closeable接口,实现这两个接口就必须实现close方法。Closeable是AutoCloseable的子接口。Java7几乎把所有的“资源类”(包括文件IO的各种类、JDBC编程的Connection、Statement等接口…)进行了改写,改写后资源类都是实现了AutoCloseable或Closeable接口,并实现了close方法。
  1021. 写到try()中的资源类的变量默认是final声明的,不能修改。
  1022. 示例代码:
  1023. ```java
  1024. @Test
  1025. public void test03() {
  1026. //从d:/1.txt(GBK)文件中,读取内容,写到项目根目录下1.txt(UTF-8)文件中
  1027. try(
  1028. FileInputStream fis = new FileInputStream("d:/1.txt");
  1029. InputStreamReader isr = new InputStreamReader(fis,"GBK");
  1030. BufferedReader br = new BufferedReader(isr);
  1031. FileOutputStream fos = new FileOutputStream("1.txt");
  1032. OutputStreamWriter osw = new OutputStreamWriter(fos,"UTF-8");
  1033. BufferedWriter bw = new BufferedWriter(osw);
  1034. ){
  1035. String str;
  1036. while((str = br.readLine()) != null){
  1037. bw.write(str);
  1038. bw.newLine();
  1039. }
  1040. } catch (FileNotFoundException e) {
  1041. e.printStackTrace();
  1042. } catch (IOException e) {
  1043. e.printStackTrace();
  1044. }
  1045. }
  1046. ```
  1047. # 第八章 Properties属性集
  1048. ## 8.1 概述
  1049. `java.util.Properties ` 继承于` Hashtable` ,来表示一个持久的属性集。它使用键值结构存储数据,每个键及其对应值都是一个字符串。该类也被许多Java类使用,比如获取系统属性时,`System.getProperties` 方法就是返回一个`Properties`对象。
  1050. ## 8.2 Properties类
  1051. ### 构造方法
  1052. - `public Properties()` :创建一个空的属性列表。
  1053. ### 基本的存储方法
  1054. * 一般下面的这些方法不用,用Map集合里面的put等方法
  1055. - `public Object setProperty(String key, String value)` : 保存一对属性。
  1056. - `public String getProperty(String key) ` :使用此属性列表中指定的键搜索属性值。
  1057. - `public Set<String> stringPropertyNames() ` :所有键的名称的集合。
  1058. ```java
  1059. //Java 1.0 的时候,是没有集合体系的。
  1060. //单列集合: Vector
  1061. //双列集合:Hashtable
  1062. //上面的类和Properties 都是1.0的时候出来的。
  1063. //之后,发现集合挺好用的,而且在大量的场景中,都能用到集合
  1064. //所以,在JDK1.2的时候,推出了集合体系。
  1065. //Properties就开始使用集合体系里面的共有方法,而原来的特有方法就不用了。
  1066. public class PropertiesDemo1 {
  1067. public static void main(String[] args) {
  1068. //1,Properties本身在Java中,是Map体系中的一员
  1069. //本身也是一个双列集合
  1070. //创建对象的时候,不用写泛型
  1071. //不写泛型,表示可以往集合中存储任意的数据类型
  1072. //但是我们一般不会这么干,一般只会把字符串存入。
  1073. Properties prop = new Properties();
  1074. //2.添加
  1075. prop.put("zhangsan","123");
  1076. prop.put("lisi","1234");
  1077. prop.put("wangwu","12345");
  1078. //3.遍历
  1079. Set<Object> keys = prop.keySet();
  1080. for (Object key : keys) {
  1081. String value = prop.get(key) + "";
  1082. System.out.println(key + ", " + value);
  1083. }
  1084. }
  1085. }
  1086. ```
  1087. ### 与流相关的方法
  1088. - `public void load(InputStream inStream)`: 从字节输入流中读取键值对。
  1089. 参数中使用了字节输入流,通过流对象,可以关联到某文件上,这样就能够加载文本中的数据了。文本数据格式:
  1090. ```properties
  1091. filename=a.txt
  1092. length=209385038
  1093. location=D:\a.txt
  1094. ```
  1095. ### 加载代码
  1096. ```java
  1097. //1.创建对象
  1098. Properties prop = new Properties();
  1099. //2.加载
  1100. //Properties集合的本地文件,有一个命名规则:XXX.properties
  1101. //会把本地properties文件当中的键值对,直接读到内存中,并存入到集合里面
  1102. //省得我们自己读取再切割了。
  1103. //细节1:
  1104. //如果配置文件中,有中文,那么需要用FileReader
  1105. //细节2:
  1106. //在实际开发中,一般来讲,我们不会在properties文件里面写中文,一般都写英文
  1107. FileInputStream fis = new FileInputStream("day10-code\\prop.properties");
  1108. prop.load(fis);
  1109. //3.打印集合
  1110. System.out.println(prop);
  1111. //用完之后,关流
  1112. fis.close();
  1113. ```
  1114. ####
  1115. > 小贴士:文本中的数据,必须是键值对形式,不可以使用空格、等号、冒号等符号分隔。
  1116. # 第九章 综合练习
  1117. ## 练习1:按照层级目录拷贝文件夹
  1118. 需求:
  1119. ​ 将某个磁盘的文件夹拷贝到另一个文件夹下去,包括文件夹中的全部信息
  1120. ​ 需要考虑子文件夹
  1121. 代码示例:
  1122. ```java
  1123. public class Test1 {
  1124. public static void main(String[] args) throws IOException {
  1125. /*需求:将某个磁盘的文件夹拷贝到另一个文件夹下去,
  1126. 包括文件夹中的全部信息,需要考虑子文件夹*/
  1127. //要拷贝的文件夹:C:\Users\moon\Desktop\aaa
  1128. //技术选型:
  1129. //字节流:拷贝
  1130. //字符流:读和写
  1131. //缓冲流:提高效率
  1132. //转换流:指定编码读写
  1133. //对象操作流/序列化流、反序列化流:把对象写到本地,读取本地文件中的对象
  1134. //因为本题是拷贝:所以选择字节流或缓冲流
  1135. //因为要考虑子文件夹,所以需要用到递归
  1136. //数据源
  1137. File src = new File("C:\\Users\\moon\\Desktop\\aaa");
  1138. //目的地
  1139. File dest = new File("C:\\Users\\moon\\Desktop\\bbb");
  1140. copyDir(src,dest);
  1141. }
  1142. //数据源 src
  1143. //目的地 dest
  1144. public static void copyDir(File src, File dest) throws IOException {
  1145. //创建目的地文件夹
  1146. //此时不需要判断,如果目的地文件夹存在,大不了创建失败。
  1147. dest.mkdirs();
  1148. File[] files = src.listFiles();
  1149. for (File file : files) {
  1150. if(file.isFile()){
  1151. //如果是文件,就拷贝
  1152. FileInputStream fis = new FileInputStream(file);//src里面的a.txt
  1153. FileOutputStream fos = new FileOutputStream(new File(dest,file.getName()));//dest 里面的a.txt
  1154. byte[] bytes = new byte[1024];
  1155. int len;
  1156. while((len = fis.read(bytes)) != -1){
  1157. fos.write(bytes,0,len);
  1158. }
  1159. fos.close();
  1160. fis.close();
  1161. }else{
  1162. //如果是文件夹,就递归
  1163. //把第一个参数里面的内容,拷贝到第二个参数里面去
  1164. //file:src --- aaa
  1165. //目的地:dest里面的aaa
  1166. copyDir(file, new File(dest,file.getName()));
  1167. }
  1168. }
  1169. }
  1170. }
  1171. ```
  1172. ## 练习2:点名器升级版
  1173. 需求:
  1174. 有一个文件里面存储了班级同学的姓名,每一个姓名占一行,要求通过程序实现随机点名器。
  1175. 第三次必定是张三同学
  1176. 核心思路:
  1177. ​ 1.定义一个文件存储学生的姓名
  1178. ​ 2.定义第二个文件记录程序运行的次数
  1179. ​ 3.先读取次数,如果是第三次,直接打印
  1180. ​ 4.如果不是第三次,则读取存储学生姓名的文件,并随机姓名
  1181. ​ 5.再把当前运行的次数写会文件,永久保存
  1182. 代码示例:
  1183. ```java
  1184. //1.获取当前程序运行的次数
  1185. BufferedReader br = new BufferedReader(new FileReader("day10-code\\count.txt"));
  1186. String line = br.readLine();
  1187. int count = Integer.parseInt(line);
  1188. //count表示程序已经运行了多少次
  1189. //表示程序又运行了一次
  1190. count++;
  1191. if (count == 3) {
  1192. System.out.println("何江");
  1193. } else {
  1194. //随机
  1195. //1.把文件中所有同学的名字都读到内存中。
  1196. ArrayList<String> list = new ArrayList<>();
  1197. BufferedReader br2 = new BufferedReader(new FileReader("day10-code\\studentname.txt"));
  1198. String line2;
  1199. while ((line2 = br2.readLine()) != null) {
  1200. list.add(line2);
  1201. }
  1202. br2.close();
  1203. //当循环结束之后,表示文件中所有同学的名字都读到集合中了
  1204. System.out.println(list);
  1205. Random r = new Random();
  1206. int randomIndex = r.nextInt(list.size());
  1207. String name1 = list.get(randomIndex);
  1208. System.out.println(name1);
  1209. }
  1210. //把count再写会文件
  1211. BufferedWriter bw = new BufferedWriter(new FileWriter("day10-code\\count.txt"));
  1212. bw.write(count + "");
  1213. bw.close();
  1214. ``