-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathchapter.java.io.xml
More file actions
1963 lines (1769 loc) · 57.8 KB
/
chapter.java.io.xml
File metadata and controls
1963 lines (1769 loc) · 57.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?xml version="1.0" encoding="UTF-8"?>
<chapter id="index"><?dbhtml dir="io" ?>
<title>IO</title>
<section id="File">
<title>取出文件名中的扩展名</title>
<programlisting>
<![CDATA[
File file = new File("HelloWorld.jpeg");
String fileName = file.getName();
String suffix = fileName.substring(fileName.lastIndexOf(".") + 1);
System.out.println(suffix);
]]>
</programlisting>
<section id="getAbsolutePath()">
<title>getAbsolutePath() 获取绝对路径</title>
<programlisting>
<![CDATA[
File configFile = new File(System.getProperty("user.dir") + configPath);
System.out.printf("configFile : %s\n", configFile.getAbsolutePath());
]]>
</programlisting>
</section>
<section id="File.mkdir()">
<title>创建目录 mkdir()</title>
<programlisting>
<![CDATA[
//判断cache目录是否存在的代码,如果不存在则创建cache目录
String path="/tmp/cache";
File dirname = new File(path);
//目录不存在
if (!dirname.isDirectory())
{
dirname.mkdir(); //创建目录
}
]]>
</programlisting>
</section>
<section>
<title>文件删除</title>
<programlisting>
<![CDATA[
public static boolean delete(String pathname) {
boolean status = false;
File file = new File(pathname);
if (file.isFile() && file.exists()) {
status = file.delete();
}
return status;
}
]]>
</programlisting>
<programlisting>
<![CDATA[
public static void deleteOnExit(String pathname) {
File file = new File(pathname);
file.deleteOnExit();
}
]]>
</programlisting>
</section>
<section>
<title>获取路径中目录和文件名</title>
<programlisting>
<![CDATA[
import java.io.File;
public class GetDirectory {
public static void main(String[] args) {
String path = "development/2026-03-01/5e021a21153a48828a2a19283b03ebaa/家庭用车选择丰田双擎的优势(甘特图).svg";
File file = new File(path);
// 获取文件所在的目录
String directory = file.getParent();
System.out.println("目录路径:" + directory);
}
}
]]>
</programlisting>
<programlisting>
<![CDATA[
import java.io.File;
public class FileNameExtractor {
public static void main(String[] args) {
String path = "development/2026-03-01/5e021a21153a48828a2a19283b03ebaa/家庭用车选择丰田双擎的优势(甘特图).svg";
File file = new File(path);
String fileName = file.getName(); // 直接获取文件名
System.out.println("提取到的文件名:" + fileName);
}
}
]]>
</programlisting>
<programlisting>
<![CDATA[
public class FileNameExtractor {
public static void main(String[] args) {
String path = "development/2026-03-01/5e021a21153a48828a2a19283b03ebaa/家庭用车选择丰田双擎的优势(甘特图).svg";
// 按 / 分割,取最后一段就是文件名
String fileName = path.split("/")[path.split("/").length - 1];
System.out.println("提取到的文件名:" + fileName);
}
}
]]>
</programlisting>
</section>
<section id="File.createTempFile">
<title>临时文件</title>
<programlisting>
<![CDATA[
package cn.netkiller.file;
import java.io.File;
import java.io.IOException;
public class CreateTempFileExample
{
public static void main(String[] args)
{
try{
//create a temp file
File temp = File.createTempFile("temp-file-name", ".tmp");
System.out.println("Temp file : " + temp.getAbsolutePath());
}catch(IOException e){
e.printStackTrace();
}
}
}
]]>
</programlisting>
<para>Temp file :
C:\Users\neo\AppData\Local\Temp\temp-file-name623426.tmp
</para>
<para>指定目录创建临时文件,运行之后将会在 /tmp/convert 目录中创建文件</para>
<programlisting>
<![CDATA[
@SneakyThrows
public InputStream convertInputStreamAmrToPcm(InputStream inputStreamAmr) {
// UUID uuid = UUID.randomUUID();
// String filename = uuid.toString();
String filename = "convert-";
File source = File.createTempFile(filename, ".amr", new File("/tmp/convert"));
File target = File.createTempFile(filename, ".pcm", new File("/tmp/convert"));
if (!target.getParentFile().isDirectory()) {
boolean directory = target.getParentFile().mkdirs();
}
log.info("Source: {}, Target: {}", source.getAbsolutePath(), target.getAbsolutePath());
source.deleteOnExit();
target.deleteOnExit();
inputStreamAmr.transferTo(new FileOutputStream(source));
boolean status = audioFormatConversion(source, target);
log.info("Amr To Pcm: {}", status);
if (!status) {
return null;
}
InputStream inputStream = new FileInputStream(target);
return inputStream;
}
]]>
</programlisting>
</section>
</section>
<section id="java.io.FileWriter">
<title>FileWriter 文本写入文件</title>
<programlisting>
<![CDATA[
import java.io.*;
public class Main {
public static void main(String[] args) {
try {
String str = "SomeMoreTextIsHere";
File newTextFile = new File("thetextfile.txt");
FileWriter fw = new FileWriter(newTextFile);
fw.write(str);
fw.close();
} catch (IOException iox) {
//do stuff with exception
iox.printStackTrace();
}
}
}
]]>
</programlisting>
</section>
<section id="java.nio.file">
<title>Files</title>
<section>
<title>删除文件</title>
<programlisting>
<![CDATA[
package cn.netkiller.test;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
public class FileDirectory {
public static void main(String[] args) throws IOException {
//如果文件不存在,抛出NoSuchFileException
//如果文件夹里面包含文件,抛出DirectoryNotEmptyException
Path path = Paths.get("D:\\data\test");
Files.delete(path); //返回值void
}
}
]]>
</programlisting>
<programlisting>
<![CDATA[
//如果文件不存在,返回false,表示删除失败(文件不存在)
//如果文件夹里面包含文件,抛出DirectoryNotEmptyException
private static void deleteIfExists() throws IOException {
Path path = Paths.get("D:\data\test1");
boolean result = Files.deleteIfExists(path);
System.out.println(result);
}
private static void deleteDirectoryStream(Path path) {
try {
Files.delete(path);
System.out.printf("删除文件成功:%s%n",path.toString());
} catch (IOException e) {
System.err.printf("无法删除的路径 %s%n%s", path, e);
}
}
// 递归删除目录,使用Files.walk遍历文件夹,然后返回 Stream<Path>,接着递归调用删除目录方法
private static void testDeleteFileDir6() throws IOException {
createMoreFiles();
Path path = Paths.get("D:\data\");
try (Stream<Path> walk = Files.walk(path)) {
walk.sorted(Comparator.reverseOrder())
.forEach(DeleteFileDir::deleteDirectoryStream);
}
}
]]>
</programlisting>
<para>walkFileTree与FileVisitor配合使用,walkFileTree方法遍历整个文件目录树,使用FileVisitor处理遍历结果(文件或文件夹)
</para>
<programlisting>
<![CDATA[
// FileVisitor的postVisitDirectory方法,注意方法中的“post”表示“后去做……”的意思,所以用来文件都处理完成之后再去处理文件夹,所以使用这个方法删除文件夹就可以有效避免文件夹内容不为空的异常,因为在去删除文件夹之前,该文件夹里面的文件已经被删除了。
private static void walkFileTree() throws IOException {
Path path = Paths.get("D:\\data");
Files.walkFileTree(path,
new SimpleFileVisitor<Path>() {
// 先去遍历删除文件
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
Files.delete(file);
System.out.printf("删除文件 : %s%n", file);
return FileVisitResult.CONTINUE;
}
// 再去遍历删除目录
@Override
public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
Files.delete(dir);
System.out.printf("删除文件夹: %s%n", dir);
return FileVisitResult.CONTINUE;
}
}
);
}
]]>
</programlisting>
</section>
<section>
<title>创建目录和文件</title>
<programlisting>
<![CDATA[
private void createMoreFiles() throws IOException {
Files.createDirectories(Paths.get("D:\data\test1\test2\test3\test4\test5\"));
Files.write(Paths.get("D:\data\test1\test2\test2.log"), "hello".getBytes());
Files.write(Paths.get("D:\data\test1\test2\test3\test3.log"), "hello".getBytes());
}
]]>
</programlisting>
</section>
</section>
<section id="BufferedWriter">
<title>BufferedWriter</title>
<programlisting>
<![CDATA[
File file = new File( fileName );
// if file doesnt exists, then create it
if ( ! file.exists( ) )
{
file.createNewFile( );
}
FileWriter fw = new FileWriter( file.getAbsoluteFile( ) );
BufferedWriter bw = new BufferedWriter( fw );
bw.write( text );
bw.close( );
]]>
</programlisting>
</section>
<section id="PrintWriter">
<title>PrintWriter</title>
<programlisting>
<![CDATA[
package cn.netkiller.io;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
public class PrintWriterTest {
public PrintWriterTest() {
// TODO Auto-generated constructor stub
}
public static void main(String[] args) throws FileNotFoundException {
// TODO Auto-generated method stub
PrintWriter output = new PrintWriter("temp.txt");
output.print("Welcome to Java!");
output.close();
}
}
]]>
</programlisting>
</section>
<section id="FileOutputStream">
<title>FileOutputStream</title>
<programlisting>
<![CDATA[
byte[] data = ...
FileOutputStream fos = new FileOutputStream(filePath)
fos.write(data, 0, data.length);
fos.flush();
fos.close();
]]>
</programlisting>
<section id="FileOutputStream.try">
<title>FileOutputStream + try 用法</title>
<programlisting>
<![CDATA[
try (FileOutputStream fileOutputStream = new FileOutputStream(filePath)) {
...
fileOutputStream.write(audioBuffer);
...
} catch (Exception e) {
throw new RuntimeException(e);
}
]]>
</programlisting>
</section>
<section id="OutputStreamWriter">
<title>OutputStreamWriter</title>
<programlisting>
<![CDATA[
File file = new File("/tmp" + File.separator + "netkiller.txt");
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(new FileOutputStream(file), "utf-8");
outputStreamWriter.write("Netkiller Java 手札");
outputStreamWriter.close();
]]>
</programlisting>
</section>
</section>
<section id="FileInputStream">
<title>FileInputStream</title>
<programlisting>
<![CDATA[
File inputFile = new File(filePath);
byte[] data = new byte[inputFile.length()];
FileInputStream fis = new FileInputStream(inputFile);
fis.read(data, 0, data.length);
fis.close();
]]>
</programlisting>
<section id="InputStreamReader">
<title>InputStreamReader</title>
<programlisting>
<![CDATA[
InputStreamReader stream = new InputStreamReader(this.getClass().getClassLoader().getResourceAsStream(filename));
]]>
</programlisting>
</section>
<section id="inputStream.transferTo()">
<title>inputStream.transferTo()</title>
<screen>
<![CDATA[
var classLoader = ClassLoader.getSystemClassLoader();
var inputStream = classLoader.getResourceAsStream("hello.txt");
var tmp = File.createTempFile("tmp", "txt");
try (var outputStream = new FileOutputStream(tmp)) {
inputStream.transferTo(outputStream);
}
]]>
</screen>
</section>
</section>
<section id="java.util.Scanner">
<title>Scanner</title>
<programlisting>
<![CDATA[
Scanner input = new Scanner(new File("temp.txt"));
System.out.print(input.nextLine());
]]>
</programlisting>
<programlisting>
<![CDATA[
package cn.netkiller.io;
import java.io.File;
import java.io.FileNotFoundException;
//import java.io.PrintWriter;
import java.util.Scanner;
public class PrintWriterTest {
private static Scanner input;
public PrintWriterTest() {
// TODO Auto-generated constructor stub
}
public static void main(String[] args) throws FileNotFoundException {
// TODO Auto-generated method stub
// PrintWriter output = new PrintWriter("temp.txt");
// output.print("Welcome to Java!");
// output.close();
input = new Scanner(new File("temp.txt"));
System.out.print(input.nextLine());
}
}
]]>
</programlisting>
<programlisting>
<![CDATA[
@Test
void testReadFile1() throws IOException {
String fileName = "D:\\test\\netkiller\\neo.txt";
try (Scanner sc = new Scanner(new FileReader(fileName))) {
while (sc.hasNextLine()) { //按行读取字符串
String line = sc.nextLine();
System.out.println(line);
}
}
try (Scanner sc = new Scanner(new FileReader(fileName))) {
sc.useDelimiter("\\|"); //分隔符
while (sc.hasNext()) { //按分隔符读取字符串
String str = sc.next();
System.out.println(str);
}
}
//sc.hasNextInt() 、hasNextFloat() 、基础数据类型等等等等。
fileName = "D:\\netkiller\\test\\neo.txt";
try (Scanner sc = new Scanner(new FileReader(fileName))) {
sc.useDelimiter("\\|"); //分隔符
while (sc.hasNextInt()) { //按分隔符读取Int
int intValue = sc.nextInt();
System.out.println(intValue);
}
}
}
]]>
</programlisting>
</section>
<section id="Files">
<title>Files</title>
<section>
<title>Files.lines</title>
<programlisting>
<![CDATA[
@Test
void testReadFile2() throws IOException {
String fileName = "D:\\test\\netkiller\\neo.txt";
// 读取文件内容到Stream流中,按行读取
Stream<String> lines = Files.lines(Paths.get(fileName));
// 随机行顺序进行数据处理
lines.forEach(line -> {
System.out.println(line);
});
}
]]>
</programlisting>
<programlisting>
<![CDATA[
// 按文件行顺序进行处理
lines.forEachOrdered(System.out::println);
// 利用CPU多和的能力,进行数据的并行处理parallel(),适合比较大的文件。
lines.parallel().forEachOrdered(System.out::println);
]]>
</programlisting>
</section>
<section>
<title>Files.readAllLines</title>
<programlisting>
<![CDATA[
@Test
void testReadFile3() throws IOException {
String fileName = "D:\\test\\netkiller\\neo.txt";
// 转换成List<String>, 要注意java.lang.OutOfMemoryError: Java heap space
List<String> lines = Files.readAllLines(Paths.get(fileName),
StandardCharsets.UTF_8);
lines.forEach(System.out::println);
}
]]>
</programlisting>
</section>
<section>
<title>Files.readAllBytes</title>
<programlisting>
<![CDATA[
@Test
void testReadFile5() throws IOException {
String fileName = "D:\\test\\netkiller\\neo.txt";
//如果是JDK11用上面的方法,如果不是用这个方法也很容易
byte[] bytes = Files.readAllBytes(Paths.get(fileName));
String content = new String(bytes, StandardCharsets.UTF_8);
System.out.println(content);
}
]]>
</programlisting>
</section>
<section>
<title>Files.newBufferedReader</title>
<programlisting>
<![CDATA[
@Test
void testReadFile6() throws IOException {
String fileName = "D:\\test\\netkiller\\neo.txt";
// 带缓冲的流读取,默认缓冲区8k
try (BufferedReader br = new BufferedReader(new FileReader(fileName))){
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
}
//java 8中这样写也可以
try (BufferedReader br = Files.newBufferedReader(Paths.get(fileName))){
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
}
}
]]>
</programlisting>
</section>
</section>
<section id="file.binary">
<title>二进制文件</title>
<section id="binary.int">
<title>理解二进制文件</title>
<para>我们运行下面一段程序,向文件 netkiller.bin 中写入一个整形数值 1 ,然后观察文件变化</para>
<programlisting>
<![CDATA[
String filename = "netkiller.bin";
DataOutputStream out = new DataOutputStream(new FileOutputStream(filename));
out.writeInt(1);
out.close();
]]>
</programlisting>
<para>打开终端,使用 xxd 命令查看二进制文件</para>
<screen>
<![CDATA[
neo@MacBook-Pro ~/workspace/netkiller % xxd -b netkiller.bin
00000000: 00000000 00000000 00000000 00000001 ....
]]>
</screen>
<para>可以看到一串二进制 00000000 00000000 00000000
00000001,运行下面程序可以讲二进制转换为十进制,注意替换掉空格。
</para>
<programlisting>
<![CDATA[
int n = Integer.valueOf("00000000 00000000 00000000 00000001".replaceAll(" ", ""), 2);
System.out.println(n);
]]>
</programlisting>
<para>运行结果是 1 ,为什前面那么多 0 呢?请运行下面一段程序</para>
<programlisting>
<![CDATA[
String filename = "netkiller.bin";
DataOutputStream out = new DataOutputStream(new FileOutputStream(filename));
out.writeInt(Integer.MAX_VALUE);
out.close();
]]>
</programlisting>
<para>现在观察结果</para>
<screen>
<![CDATA[
neo@MacBook-Pro ~/workspace/netkiller % xxd -b netkiller.bin
00000000: 01111111 11111111 11111111 11111111 ....
]]>
</screen>
<programlisting>
<![CDATA[
int n = Integer.valueOf("01111111 11111111 11111111 11111111".replaceAll(" ", ""), 2);
System.out.println(n);
]]>
</programlisting>
<para>输出结果是 2147483647, 这是 int 得最大值,2147483647 + 1 会怎么样呢?</para>
<programlisting>
<![CDATA[
String filename = "netkiller.bin";
DataOutputStream out = new DataOutputStream(new FileOutputStream(filename));
out.writeInt(Integer.MAX_VALUE + 1);
out.close();
System.out.println(Integer.MAX_VALUE + 1);
]]>
</programlisting>
<para>输出结果是 -2147483648,正确应该是 2147483648
这就是整形溢出。整形变量得二进制表示方法是4个字节长度32位 00000000 00000000 00000000 00000000 到
01111111 11111111 11111111 11111111 , 其中第一位0表示正数1表示负数。
</para>
<screen>
<![CDATA[
neo@MacBook-Pro ~/workspace/netkiller % xxd -b netkiller.bin
00000000: 10000000 00000000 00000000 00000000 ....
]]>
</screen>
<para>整形溢出演示,超出整形范围怎么办? 使用 Long 型。</para>
<screen>
<![CDATA[
System.out.println(Integer.MAX_VALUE);
System.out.println(Integer.MAX_VALUE + 1);
System.out.println(Integer.MIN_VALUE);
System.out.println(Integer.MIN_VALUE - 1);
输出结果如下:
2147483647
-2147483648
-2147483648
2147483647
]]>
</screen>
<para>负数演示</para>
<programlisting>
<![CDATA[
String filename = "netkiller.bin";
DataOutputStream out = new DataOutputStream(new FileOutputStream(filename));
out.writeInt(-1);
out.writeInt(Integer.MAX_VALUE + 1);
out.close();
]]>
</programlisting>
<para>-1 得结果是 11111111 11111111 11111111 11111111 </para>
<screen>
<![CDATA[
neo@MacBook-Pro ~/workspace/netkiller % xxd -b netkiller.bin
00000000: 11111111 11111111 11111111 11111111 ....
]]>
</screen>
<para>现在我们存储两个整形数值</para>
<programlisting>
<![CDATA[
String filename = "netkiller.bin";
DataOutputStream out = new DataOutputStream(new FileOutputStream(filename));
out.writeInt(1);
out.writeInt(-1);
out.close();
]]>
</programlisting>
<para>很清楚的看到里面有两个数值,1 和 -1 </para>
<screen>
<![CDATA[
neo@MacBook-Pro ~/workspace/netkiller % xxd -c 4 -b netkiller.bin
00000000: 00000000 00000000 00000000 00000001 ....
00000004: 11111111 11111111 11111111 11111111 ....
]]>
</screen>
<para>读取二进制文件中的 int 数据</para>
<programlisting>
<![CDATA[
DataInputStream in = new DataInputStream(new BufferedInputStream(new FileInputStream(filename)));
try {
int i = in.readInt();
System.out.println(i);
} catch (EOFException e) {
e.printStackTrace();
}
]]>
</programlisting>
</section>
<section id="binary.byte">
<title>byte 类型</title>
<programlisting>
<![CDATA[
String filename = "netkiller.bin";
DataOutputStream out = new DataOutputStream(new FileOutputStream(filename));
out.writeByte(1);
out.close();
]]>
</programlisting>
<para>byte 只占用一个字节8位</para>
<screen>
<![CDATA[
neo@MacBook-Pro ~/workspace/netkiller % xxd -c 4 -b netkiller.bin
00000000: 00000001
]]>
</screen>
<para>如果写入 -1 结果是,由此得出 第一位 0 是正数,1 是负数,可以得出他的取值范围 -128 ~
127。超出范围也会溢出。
</para>
<screen>
<![CDATA[
neo@MacBook-Pro ~/workspace/netkiller % xxd -c 4 -b netkiller.bin
00000000: 11111111
]]>
</screen>
<para>常常写入最小值与最大值</para>
<programlisting>
<![CDATA[
String filename = "netkiller.bin";
DataOutputStream out = new DataOutputStream(new FileOutputStream(filename));
out.writeByte(Byte.MIN_VALUE);
out.writeByte(Byte.MAX_VALUE);
out.close();
]]>
</programlisting>
<para>运行结果</para>
<screen>
<![CDATA[
neo@MacBook-Pro ~/workspace/netkiller % xxd -c 1 -b netkiller.bin
00000000: 10000000 .
00000001: 01111111 .
]]>
</screen>
<para>写入一个字符</para>
<programlisting>
<![CDATA[
String filename = "netkiller.bin";
DataOutputStream out = new DataOutputStream(new FileOutputStream(filename));
out.writeBytes("a");
out.close();
]]>
</programlisting>
<para>写入结果</para>
<screen>
<![CDATA[
neo@MacBook-Pro ~/workspace/netkiller % xxd -c 1 -b netkiller.bin
00000000: 01100001 a
]]>
</screen>
<para>从 ASCII 表中查出 01100001 十进制 97 十六进制 61 对应字母 a</para>
<para>写入一段字符串</para>
<programlisting>
<![CDATA[
String filename = "netkiller.bin";
DataOutputStream out = new DataOutputStream(new FileOutputStream(filename));
out.writeBytes("http://www.netkiller.cn");
out.close();
]]>
</programlisting>
<para>运行结果</para>
<screen>
<![CDATA[
neo@MacBook-Pro ~/workspace/netkiller % xxd -c 8 -b netkiller.bin
00000000: 01101000 01110100 01110100 01110000 00111010 00101111 00101111 01110111 http://w
00000008: 01110111 01110111 00101110 01101110 01100101 01110100 01101011 01101001 ww.netki
00000010: 01101100 01101100 01100101 01110010 00101110 01100011 01101110 ller.cn
]]>
</screen>
<para>读取二进制文件中的 byte 字符串,readAllBytes() 可以一次读取所有 byte 到 byte[] 中。
</para>
<programlisting>
<![CDATA[
DataInputStream in = new DataInputStream(new BufferedInputStream(new FileInputStream(filename)));
try {
System.out.println(new String(in.readAllBytes()));
} catch (EOFException e) {
e.printStackTrace();
}
]]>
</programlisting>
<para>readByte() 逐字节读取</para>
<programlisting>
<![CDATA[
DataInputStream in = new DataInputStream(new BufferedInputStream(new FileInputStream(filename)));
try {
char c = ' ';
while (true) {
try {
c = (char) in.readByte();
System.out.print(c);
} catch (EOFException e) {
System.out.println();
break;
}
}
} catch (Exception e) {
e.printStackTrace();
}
]]>
</programlisting>
<para>现在我们已经掌握了 byte 的操作方法,现在我们来做一个例子,读取 int 数据,int 是由 4
个字节组成一组。所以我们每次取 4个字节。
</para>
<programlisting>
<![CDATA[
// 这个例子中,我们写入三个数值到 netkiller.bin 文件,分别是 1024,-128,2147483647
String filename = "netkiller.bin";
DataOutputStream out = new DataOutputStream(new FileOutputStream(filename));
out.writeInt(1024);
out.writeInt(-128);
out.writeInt(Integer.MAX_VALUE);
out.close();
]]>
</programlisting>
<para>二进制文件如下</para>
<screen>
<![CDATA[
neo@MacBook-Pro ~/workspace/netkiller % xxd -c 4 -b netkiller.bin
00000000: 00000000 00000000 00000100 00000000 ....
00000004: 11111111 11111111 11111111 10000000 ....
00000008: 01111111 11111111 11111111 11111111 ....
]]>
</screen>
<para>从二进制文件读出 int 数据。</para>
<programlisting>
<![CDATA[
String filename = "netkiller.bin";
FileInputStream stream = new FileInputStream(filename);
byte[] buffer = new byte[4];
while (stream.read(buffer) != -1) {
ByteBuffer byteBuffer = ByteBuffer.wrap(buffer);
System.out.println(byteBuffer.getInt());
}
]]>
</programlisting>
<para>运行结果</para>
<screen>
<![CDATA[
1024
-128
2147483647
]]>
</screen>
</section>
<section id="binary.boolean">
<title>boolean 布尔型</title>
<para>我们想文件写入两个布尔类型,一个是 true, 另一个是 false</para>
<programlisting>
<![CDATA[
String filename = "netkiller.bin";
DataOutputStream out = new DataOutputStream(new FileOutputStream(filename));
out.writeBoolean(true);
out.writeBoolean(false);
out.close();
]]>
</programlisting>
<para>运行结果可以看出 boolean 使用了一个字节,最后一位 1 表示true, 0 表示
false。所以对于二进制文件最小单位就是 byte 字节,虽然boolean型只需要一个 1 bit
位,但是存储的最小单位是字节,所以前面需要补7个零 0000000。
</para>
<screen>
<![CDATA[
neo@MacBook-Pro ~/workspace/netkiller % xxd -c 1 -b netkiller.bin
00000000: 00000001 .
00000001: 00000000 .
]]>
</screen>
<para>使用 ls 命令可以看这个文件占用了 2B(两个字节)</para>
<screen>
<![CDATA[
neo@MacBook-Pro ~/workspace/netkiller % ll netkiller.bin
-rw-r--r-- 1 neo staff 2B Oct 18 13:47 netkiller.bin
]]>
</screen>
<para>读取二进制文件中的 boolean 数据</para>
<programlisting>
<![CDATA[
DataInputStream in = new DataInputStream(new BufferedInputStream(new FileInputStream(filename)));
try {
boolean bool = in.readBoolean();
System.out.println(bool);
} catch (EOFException e) {
e.printStackTrace();
}
]]>
</programlisting>
</section>
<section id="binary.long">
<title>Long 型</title>
<programlisting>
<![CDATA[
String filename = "netkiller.bin";
DataOutputStream out = new DataOutputStream(new FileOutputStream(filename));
out.writeLong(1);
out.close();
]]>
</programlisting>
<para>有了上面 int 型数据的经验,下面一看你就会明白。long 型采用 8 个字节保存数据,是 int
的一倍。取值范围这里就不多说了,也会存在溢出现象。
</para>
<screen>
<![CDATA[
neo@MacBook-Pro ~/workspace/netkiller % xxd -c 8 -b netkiller.bin
00000000: 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000001 ........
]]>
</screen>
<para>取值范围</para>
<programlisting>
<![CDATA[
String filename = "netkiller.bin";
DataOutputStream out = new DataOutputStream(new FileOutputStream(filename));
out.writeLong(Long.MIN_VALUE);
out.writeLong(Long.MAX_VALUE);
out.close();
]]>
</programlisting>
<para>输出文件</para>
<screen>
<![CDATA[
neo@MacBook-Pro ~/workspace/netkiller % xxd -c 8 -b netkiller.bin
00000000: 10000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 ........
00000008: 01111111 11111111 11111111 11111111 11111111 11111111 11111111 11111111 ........
]]>
</screen>
<para>读取二进制文件中的 long 数据</para>
<programlisting>
<![CDATA[
DataInputStream in = new DataInputStream(new BufferedInputStream(new FileInputStream(filename)));
try {
long l = in.readLong();
System.out.println(l);
} catch (EOFException e) {
e.printStackTrace();
}
]]>
</programlisting>
</section>
<section id="binary.char">
<title>char 类型</title>
<para>有符号 signed char 类型的范围为 -128~127</para>
<para>无符号 unsigned char 的范围为0~ 255</para>
<para>char 与 byte 操作类似,我们首先去 ASCII 表查找字符 A 对应 65,我们将 65
写入二进制文件。然后读取该字符,输出结果是 A。
</para>
<programlisting>
<![CDATA[
String filename = "netkiller.bin";
DataOutputStream out = new DataOutputStream(new FileOutputStream(filename));
out.writeChar(65);
out.close();
DataInputStream in = new DataInputStream(new BufferedInputStream(new FileInputStream(filename)));