package byteOperate;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
public class FileInputStreamDemo {
/**
*a.文件的读取
*1.建立联系 File对象
*2.选择流 输入流 InputStream(抽象父类) + FileInputStream
* @ NicolasKs
*/
public static void main(String[] args) {
File file =new File("E:/inputTest.txt");
InputStream inputStream=null;
try {
inputStream=new FileInputStream(file);
byte[] cache=new byte[1];
int length=inputStream.read(cache);
while(-1!=length){
int a = cache[0];
if(a>=0&&a<=127)
System.out.print((char)a);
else{
int nextByte = inputStream.read();
byte[] bytes=new byte[2];
bytes[0]=cache[0];
bytes[1]=(byte) nextByte;
System.out.print(new String(bytes));
}
length = inputStream.read(cache);
}
} catch (FileNotFoundException e) {
System.out.println("文件没有找到");
e.printStackTrace();
} catch (IOException e) {
System.out.println("文件读取异常");
e.printStackTrace();
}finally{
try {
if(inputStream!=null)
inputStream.close();
} catch (IOException e) {
System.out.println("输入流关闭失败");
e.printStackTrace();
}
}
}
}
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
public class FileInputStreamDemo {
/**
*a.文件的读取
*1.建立联系 File对象
*2.选择流 输入流 InputStream(抽象父类) + FileInputStream
*3.操作 byte[] cache = new byte[1024] + read()
输出(打印出来)
*4.解决乱码问题
* @ NicolasKs
*/
public static void main(String[] args) {
File file =new File("E:/inputTest.txt");
InputStream inputStream=null;
try {
inputStream=new FileInputStream(file);
byte[] cache=new byte[1];
int length=inputStream.read(cache);
while(-1!=length){
int a = cache[0];
if(a>=0&&a<=127)
System.out.print((char)a);
else{
int nextByte = inputStream.read();
byte[] bytes=new byte[2];
bytes[0]=cache[0];
bytes[1]=(byte) nextByte;
System.out.print(new String(bytes));
}
length = inputStream.read(cache);
}
} catch (FileNotFoundException e) {
System.out.println("文件没有找到");
e.printStackTrace();
} catch (IOException e) {
System.out.println("文件读取异常");
e.printStackTrace();
}finally{
try {
if(inputStream!=null)
inputStream.close();
} catch (IOException e) {
System.out.println("输入流关闭失败");
e.printStackTrace();
}
}
}
}