filewriter只能接受字符串形式的参数,也就是说只能把内容存到文本文件。相对于文本文件,采用二进制格式的文件存储更省空间。
inputstream用于按字节从输入流读取数据。其中的int read()方法读取一个字节,这个字节以整数形式返回0到255之间的一个值。为什么读一个字节,而不直接返回一个byte类型的值?
因为byte类型最高位是符号位,它所能表示的最大的正整数是127。
inputstream只是一个抽象类,不能实例化。filelnputstream是inputstream的子类,用于从文件中按字节读取。
public static void main(string[] args) throws ioexception {string filepath = "d:/test.txt"; file file = new file (filepath); //根据文件路径创建一个文件对象//如果找不到文件,会抛出filenotfoundexception异常filelnputstream filelnput = new filelnputstream(file);}filelnput.close (); //关闭文件输入流,如果无法正常关闭,会抛出ioexception异常
outputstream中的write(int b)方法用于按字节写出数据。fileoutputstream用于按字节把数据写到文件。例如,按字节把内容从一个文件读出来,并写入另外一个新文件,也就是文件复制功能。
file fileln = new file ("source. txt"); //打开源文件file fileout = new file ("target.txt”); //打开写入文件,也就是目标文件filelnputstream streamln = new filelnputstream (fileln); //根据源文件构建输入流fileoutputstream streamout = new fileoutputstream (fileout); //根据目标文件构建输出流int c;//从源文件中按字节读入数据,如果内容还没读完,则继续while ((c = streamln.read()) != -1) {streamout .write (c); //写入目标文件}streamln.close。; //关闭输入流streamout.close(); //关闭输出流
判断文件是否已经存在,如果不存在则生成这个文件。
file datafile = new file(dicdir + datadic);if (!datafile.exists()) {//如果文件不存在则写入文件}
用file.mkdirs()方法可以创建多级目录。例如,当一个目录不存在时,就创建它。
file tempdir = new file(imgpath);if(!tempdir.exists()){tempdir.mkdirs();}
众多java培训视频,尽在,欢迎在线学习!
以上就是java怎么打开二进制文件的详细内容。