文件读写java代码 java文件读取和写入

【文件读写java代码 java文件读取和写入】
JAVA操作文件在经常会使用到,本文汇总了部分JAVA操作文件的读取常用工具类,希望可以帮到大家 。直接上代码 。
一、读取文件成字节 将文件内容转为字节,需要使用到FileInputStream文件字节输入流,将文件输入到文件字节输入流中,使用FileInputStream的available()方法获取与之关联的文件的字节数,然后使用read()方法读取数据,最后记得关闭文件字节流即可 。
//读取文件成字节数组public static byte[] file2byte(String path){try {FileInputStream in =new FileInputStream(new File(path));byte[] data=https://www.haocat.cn/shenghuo/new byte[in.available()];in.read(data);in.close();return data;} catch (Exception e) {e.printStackTrace();return null;}} 二、将字节写入文件 与一中的读取文件成字节类似,字节写入文件使用FileOutputStream流,即可将字节写入到文件中 。调用FileOutputStream的write()方法,写入数据,之后关流 。
//将字节数组写入文件public static void byte2file(String path,byte[] data) {try {FileOutputStream outputStream=new FileOutputStream(new File(path));outputStream.write(data);outputStream.close();} catch (Exception e) {e.printStackTrace();}} 三、按行读取文件成list 经常遇到需要将一个文档中的文本按行输出,这是我们可以使用BufferedReader 和 InputStreamReader流处理 。具体代码如下 。
//按行读取文件成listpublic static ArrayList file2list(String path,String encoder) {ArrayList alline=new ArrayList();try {BufferedReader in =new BufferedReader(new InputStreamReader(new FileInputStream(path),encoder));String str=new String();while ((str=in.readLine())!=null) {alline.add(str);}in.close();} catch (Exception e) {e.printStackTrace();}return alline;} 四、输出list到文件 //输出list到文件public static void list2file(String path,ArrayList data,String encoder) {try {BufferedWriter out =new BufferedWriter(new OutputStreamWriter(new FileOutputStream(path),encoder));for (String str:data) {out.write(str);out.new

    推荐阅读