1.输入流读取文件中的字符串
package com.ydlclass.feature;
import org.junit.Test;
import java.io.*;
public class IOTest {
//文件流的使用步骤,例如读取a.t
@Test
public void testRead1() throws FileNotFoundException {
String path = "E:\\元气壁纸缓存\\img_cache\\a.txt";
File file = new File(path);
FileInputStream fileInputStream = new FileInputStream(file);//使用一个文件输入流,对接到文件上面去
int read;
int i = 0;
byte[] bytes = new byte[10];
try {
while ((read = fileInputStream.read()) != -1){
byte b = (byte)read;
bytes[i] = b;
i++;
}
System.out.println(new String(bytes));
} catch (IOException e) {
e.printStackTrace();
}
}
@Test
//第二个read方法的使用以及返回值的含义,参数中需要一个byte数组保存起来;返回值是读取的字节个数
public void testRead2() throws IOException {
String path = "E:\\元气壁纸缓存\\img_cache\\a.txt";
File file = new File(path);
InputStream inputStream = new FileInputStream(file);
byte[] bytes = new byte[10];
int read;
while ((read = inputStream.read(bytes)) != -1){
System.out.println(new String(bytes,0,bytes.length - 1));//使用这种方式避免字符串之后的为乱码
}
//替换掉上面的内容
//String path1 = "E:\\元气壁纸缓存\\img_cache\\a.txt";
//File file1 = new File(path);
//InputStream inputStream1 = new FileInputStream(file);
//byte[] bytes1 = new byte[10];
//int read1;
//StringBuilder sb = new StringBuilder();
//while ((read1 = inputStream.read(bytes)) != -1){
// //每次读出多少个字节,就将多少个字节变为字符串
// String s = new String(bytes,0,read1);
// sb.append(s);
//}
//System.out.println(sb);
}
}