|
1 | 1 | package com.jay; |
2 | 2 |
|
| 3 | +import java.io.FileInputStream; |
3 | 4 | import java.io.IOException; |
4 | 5 | import java.io.InputStream; |
5 | 6 |
|
|
11 | 12 | */ |
12 | 13 | public class InputStreamTest { |
13 | 14 | public static void main(String[] args) throws IOException { |
14 | | - InputStream inputStream = InputStreamTest.class.getResourceAsStream("/inputTest.txt"); |
| 15 | + String fileName = InputStreamTest.class.getResource("/inputTest.txt").getFile(); |
| 16 | +// readString1(fileName); |
| 17 | + readString2(fileName); |
| 18 | + } |
| 19 | + |
| 20 | + /** |
| 21 | + * 以字节为单位读取文件,常用于读二进制文件,如图片、声音、影像等文件。 |
| 22 | + * 当然也是可以读字符串的。 |
| 23 | + * |
| 24 | + * @param fileName |
| 25 | + */ |
| 26 | + public static void readString1(String fileName) throws IOException { |
| 27 | +// FileInputStream 用于读取诸如图像数据之类的原始字节流,读取字符流,请使用FileReader |
| 28 | + InputStream is = new FileInputStream(fileName); |
| 29 | + StringBuilder stringBuilder; |
15 | 30 | try { |
16 | | - int data; |
17 | | - while ((data=inputStream.read()) != -1) { |
18 | | - System.out.println(data); |
| 31 | + stringBuilder = new StringBuilder(); |
| 32 | + byte[] bytes = new byte[1024]; |
| 33 | + while (is.read(bytes) != -1) { |
| 34 | + stringBuilder.append(bytes); |
19 | 35 | } |
| 36 | + } finally { |
| 37 | + if (is != null) { |
| 38 | + is.close(); |
| 39 | + } |
| 40 | + } |
| 41 | + System.out.println("读取到的结果:" + stringBuilder.toString()); |
| 42 | + } |
| 43 | + |
| 44 | + /** |
| 45 | + * 按字节读取字符串,一次性读取完 |
| 46 | + * @param fileName |
| 47 | + * @throws IOException |
| 48 | + */ |
| 49 | + public static void readString2(String fileName) throws IOException { |
| 50 | + InputStream inputStream = new FileInputStream(fileName); |
| 51 | + try { |
| 52 | + // size 为字串的长度 ,这里一次性读完 |
| 53 | + byte[] bytes = new byte[inputStream.available()]; |
| 54 | + inputStream.read(bytes); |
| 55 | + System.out.println("读取到的结果是:"+new String(bytes,"UTF-8")); |
20 | 56 | } finally { |
21 | 57 | if (inputStream != null) { |
22 | 58 | inputStream.close(); |
23 | 59 | } |
24 | 60 | } |
| 61 | + |
25 | 62 | } |
26 | 63 | } |
0 commit comments