文件字节流
文件字节流
在Windows下
绝对路径:C://User/test.txt 相对路径:test.txt
文件字节输入流:
InputStream只是⼀个抽象类,要使⽤还需要具体的实现类。关于InputStream的实现类有很多,基 本可以认为不同的输⼊设备都可以对应⼀个InputStream类,我们现在只关⼼从⽂件中读取,所以使 ⽤FileInputStream
当使用完成一个流之后,必须关闭这个流来完成对资源的释放,否则资源会一直被占用:
public static void main(String[] args) {FileInputStream inputStream = null;try{inputStream=new FileInputStream("test.txt");} catch (FileNotFoundException e) {throw new RuntimeException(e);}finally {if(inputStream!=null){try {inputStream.close();} catch (IOException e) {throw new RuntimeException(e);}}}}
简化写法(语法糖):
public static void main(String[] args) {try (FileInputStream stream=new FileInputStream("test.txt")){System.out.println(stream);}catch (IOException e){e.printStackTrace();}}
英文字母占一个字节,中文占三个字节
public static void main(String[] args) {try (FileInputStream stream=new FileInputStream("test.txt")){//剩余多少个字节System.out.println(stream.available());//读一个字符int x =stream.read();System.out.println((char) x);//读所有的,前面读取了第一个字母H,此处从后开始读取int i;while ((i=stream.read())!=-1){System.out.print((char) i);}//所有内容读取完毕,后面的都不输出了//分开看方法byte[] bytes =new byte[3];while (stream.read(bytes)!=-1)System.out.println(new String(bytes)); //仅限纯文本变成字符串打印出来byte[] bytes1=new byte[stream.available()];stream.read(bytes1);System.out.println(new String(bytes1));//跳过n个字节读取stream.skip(3);System.out.println((char) stream.read());}catch (IOException e){e.printStackTrace();}}
文件字节输出流:
//文件字节输出流try(FileOutputStream stream1=new FileOutputStream("test1.txt",true)) { //true表示开启追加模式stream1.write('c');stream1.write("Hello World!".getBytes());stream1.write("Hello World!".getBytes(),3,3);//从3开始写3个长度:lo ;stream1.flush();//建议在最后执行一次刷新操作(强制写入)来保证数据正确写入到硬盘文件当中}catch (IOException e){e.printStackTrace();}
拷贝文件:
//拷贝文件try (FileInputStream in =new FileInputStream("test,txt");FileOutputStream out=new FileOutputStream("test2.txt")){int s;while ((s=in.read())!=-1)out.write(s);//如果文件很大,加快拷贝速度:byte[] bytes2=new byte[1024];int len;while ((len=in.read(bytes2))!=-1){out.write(bytes2,0,len);}}catch (IOException e){e.printStackTrace();}