您好,欢迎来到三六零分类信息网!老站,搜索引擎当天收录,欢迎发信息

java中IO流对文件操作的代码示例

2025/2/18 22:47:45发布20次查看
本篇文章给大家带来的内容是关于java中io流对文件操作的代码示例,有一定的参考价值,有需要的朋友可以参考一下,希望对你有所帮助。
io流
按照分类 有两种分类  
流向方向: 有输入流和输出流
按照操作类型有:字节流和字符流
按照流向方向
字节流的一些操作 //读文件 fileinputstream fis = new fileinputstream("java.txt"); int temp = fis.read()//一次读取一个字节 system.out.println(temp); //打印的字母的码值 读取完返回-1 system.out.println((char)temp);//打印字母 byte[] arr = new byte[6]; //定义byte数组告诉系统一次读取几个字节,减少内存和硬盘之间的通信,可以提高效率 int temp = bis.read(arr); //有参的read方法返回的int值是读取了几个字节 system.out.println(new string(arr, 0, temp)); // //写文件 fileoutputstream fos = new fileoutputstream("file" + file.separator + "1024.txt",true); //如果该文件不存在,则会自动创建 //传入true会在文件内容的后面写入文字,而不会覆盖之前的内容 //开发中文件分隔符最好不要直接写\ 而是写 file.separator string msg = "hello world"; fos.write("\n".getbytes());//换行,并向文件写入 string.getbytes() 因为要以字节的形式传入 fos.write(msg.getbytes()); string msg = "好好学习"; //一个汉字占2个字节,向里面一次传入3个字节会导致乱码 fos.write(msg.getbytes(), 0, 3); byte[] arr = new byte[6];//一次性写这么多字节 int temp = fis.read(arr); fos.write(arr, 0, temp); fos.flush();//刷新 //新的jdk7写法是在try括号()里面写文件的链接, 这样最后就不用关闭了,会自动关闭 //缓冲输入流底层默认创建一个大小是8192长度的byte数组 bufferedinputstream bis = new bufferedinputstream(new fileinputstream("java.txt")); bufferedoutputstream bos = new bufferedoutputstream(new fileoutputstream("file" + file.separator + "good.txt")); int temp = bis.read();//temp依然为ascii玛 每次一个
一些练习
利用bufferedinputstream 和 bufferedoutputstream 实现将一个文件copy到另一个文件
package com.wpbxx.stream;import java.io.bufferedinputstream;import java.io.bufferedoutputstream;import java.io.file;import java.io.fileinputstream;import java.io.filenotfoundexception;import java.io.fileoutputstream;import java.io.ioexception;public class bufferfilecopy { public static void main(string[] args) { bufferedinputstream bis = null; bufferedoutputstream bos = null; try { bis = new bufferedinputstream(new fileinputstream("java.txt")); bos = new bufferedoutputstream(new fileoutputstream("file" + file.separator + "good.txt")); int temp; while((temp = bis.read()) != -1){ bos.write(temp); } bos.flush(); } catch (filenotfoundexception e) { e.printstacktrace(); } catch (ioexception e) { e.printstacktrace(); } finally{ try { bis.close(); bos.close(); } catch (ioexception e) { e.printstacktrace(); } } }}
文件的加密 将一个字节异或一个数字实现 在传输时进行文件的加密
package com.wpbxx.stream;import java.io.bufferedinputstream;import java.io.bufferedoutputstream;import java.io.fileinputstream;import java.io.filenotfoundexception;import java.io.fileoutputstream;import java.io.ioexception;public class codefile { public static void main(string[] args) { //jdk7新写法 try ( bufferedinputstream bis = new bufferedinputstream(new fileinputstream("图片.png")); bufferedoutputstream bos = new bufferedoutputstream(new fileoutputstream("code.png")); ) { int temp; while((temp = bis.read()) != -1){ bos.write(temp ^ 88); } } catch (filenotfoundexception e) { e.printstacktrace(); } catch (ioexception e) { e.printstacktrace(); } }}
文件解密
package com.wpbxx.stream;import java.io.bufferedinputstream;import java.io.bufferedoutputstream;import java.io.fileinputstream;import java.io.filenotfoundexception;import java.io.fileoutputstream;import java.io.ioexception;public class decodefile { public static void main(string[] args) { try (bufferedinputstream bis = new bufferedinputstream(new fileinputstream("code.png")); bufferedoutputstream bos = new bufferedoutputstream(new fileoutputstream("decode.png"));) { int temp; while ((temp = bis.read()) != -1) { bos.write(temp ^ 88); } } catch (filenotfoundexception e) { e.printstacktrace(); } catch (ioexception e) { e.printstacktrace(); } }}
字符流的一些操作 可以解决乱码的问题
//读 //注意:字符流不能读取非文本文件 filereader fr = new filereader("java.txt"); int temp; while ((temp = fr.read()) != -1) { system.out.println((char) temp); //一次一个字符 } //使用缓冲字符流 bufferedreader br = new bufferedreader(new filereader("word.txt")); string msg; while((msg = br.readline()) != null){ //一次可以读取一行 system.out.println(msg); } //写 filewriter fw = new filewriter("word.txt"); fw.write("我喜欢学习java"); fw.write(97); bufferedwriter bw = new bufferedwriter(new filewriter("newbuffered.txt")); bw.write("你好"); bw.newline();//回车换行 bw.write("java");
同样是copy文件
package com.wpbxx.chario;import java.io.bufferedreader;import java.io.bufferedwriter;import java.io.file;import java.io.filenotfoundexception;import java.io.filereader;import java.io.filewriter;import java.io.ioexception;/** * 使用缓冲流拷贝文件 * 注意:字符流不能读取非文本文件 */public class bufferfilecopy { public static void main(string[] args) { try (bufferedreader br = new bufferedreader(new filereader("java.txt")); bufferedwriter bw = new bufferedwriter(new filewriter("file" + file.separator + "hellojava.txt")); ) { string msg; while((msg = br.readline()) != null){ bw.write(msg); bw.newline(); } bw.flush(); } catch (filenotfoundexception e) { e.printstacktrace(); } catch (ioexception e1) { e1.printstacktrace(); } }}
通过java中的file类实现对文件的一些操作
file file1 = new file("d:\\hello.txt"); //如果文件存在,就不创建了,返回false,如果不存在就会创建,返回true system.out.println(file1.createnewfile()); file file2 = new file("d:\\new"); //如果文件夹存在,就不创建了,返回false,如果不存在就会创建,返回true system.out.println(file2.mkdir()); file file3 = new file("d:\\wpbxx\\1024"); //可以创建多级目录,如果文件夹存在,就不创建了,返回false,如果不存在就会创建,返回true system.out.println(file3.mkdirs()); file file4 = new file("d:\\wpbxx\\1024.txt"); //只能创建文件夹 system.out.println(file4.mkdirs()); file file5 = new file("1026.txt"); //如果不写盘符,会默认在项目的根目录里面创建 system.out.println(file5.createnewfile()); system.out.println(file5.exists()); //旧名字 file oldfile1 = new file("d:\\world.txt"); //新名字 file newfile1 = new file("d:\\wpbxx\\java.txt"); //如果两个文件路径不一致,则会将旧文件剪切到新的文件路径中再重命名 oldfile1.renameto(newfile1); //不会将文件放到回收站中,而是直接删除 file del = new file("d:\\wpbxx\\java.txt"); file del1 = new file("d:\\wpbxx"); //如果文件夹下有其他文件,则不会删除 system.out.println(del1.delete()); file file2 = new file("d:\\new.txt"); //判断是否是文件夹 system.out.println(file2.isdirectory()); //判断是否是文件 system.out.println(file2.isfile()); //判断文件是否存在 system.out.println(file2.exists()); file file3 = new file("d:\\hidden"); //判断文件是否隐藏 system.out.println(file3.ishidden()); file file1 = new file("1024.txt"); //查看绝对路径 system.out.println(file1.getabsolutepath()); //文件的大小,单位是字节 system.out.println(file1.length()); //最后修改时间 date date = new date(file1.lastmodified()); simpledateformat sdf = new simpledateformat("yyyy-mm-dd"); system.out.println(sdf.format(date)); file file2 = new file("f:\\wpbxx\\代码\\code\\chapter-08"); //获取目录下的同级文件或文件夹的名称 string[] namearray = file2.list(); for(string name : namearray){ system.out.println(name); }
几个小练习
package com.wpbxx.exercise;import java.io.file;import java.util.scanner;/** * 问题:从键盘接收一个路径,将这个路径下的所有文件和文件夹的名字按照层级打印。 * 例如: * wpbxx * java * xxx.java * xxx.jpg * php * xxx.php * readme.txt * * 分析:获取路径file对象中的file数组 * 遍历数组,取得file对象 * 打印文件或文件夹的名字 * 如果是一个文件夹的话,使用递归重复上面的操作 */public class filenames { //用来记录缩进的次数 private static int count = 0; public static void main(string[] args) { file file = getfile(); getfilenames(file); } //每次调用该方法时,说明进入到一个新的文件夹的内部,需要增加一个缩进 private static void getfilenames(file file) { //获取路径file对象中的file数组 file[] filearray = file.listfiles(); //遍历数组,取得file对象 for(int i=0; i<filearray.length; i++){ //通过遍历count来控制打印几个缩进 for(int j=0; j<count; j++){ system.out.print("\t"); } //打印文件或文件夹的名字 system.out.println(filearray[i]); //如果是一个文件夹的话,使用递归重复上面的操作 if(filearray[i].isdirectory()){ count++; getfilenames(filearray[i]);//数组遍历完最后一个file对象时,说明当前文件夹已经遍历结束,需要做自减运算 count--; } } } //获取用户输入路径的file对象 private static file getfile() { system.out.println("请输入一个文件夹路径:"); scanner sc = new scanner(system.in); //获取用户输入的路径,用户输入的路径有可能是错误的,需要进行判断 while(true){ string input = sc.nextline(); file file = new file(input); if(!file.exists()){ system.out.println("您输入的文件路径有误,请重新输入文件路径:"); }else if(file.isfile()){ //如果用户输入的路径是一个文件 system.out.println("您输入的路径是一个文件,请输入一个文件夹的路径"); }else{ return file; } } } }
package com.wpbxx.exercise;import java.io.bufferedinputstream;import java.io.bufferedoutputstream;import java.io.file;import java.io.fileinputstream;import java.io.filenotfoundexception;import java.io.fileoutputstream;import java.io.ioexception;/** * 问题:收费版软件有试用次数,利用io流的知识,模拟一个可以试用3次的功能,打开3次之后提示用户购买正版软件 * * 分析:将试用的次数做加密处理后写到txt文件中 * 使用io流相关的知识将txt文件中的内容读取到内存中 * 如果读取的内容小于0时提示用户购买正版软件 * 如果大于0小于等于3时,将试用次数做自减运算之后写出到txt文件中 */public class trial { public static void main(string[] args) { //code(); bufferedinputstream bis = null; bufferedoutputstream bos = null; try { bis = new bufferedinputstream(new fileinputstream("src" + file.separator + "com" + file.separator + "monkey1024" + file.separator + "exercise" + file.separator + "config.txt")); int temp = bis.read(); //解密处理 int count = temp ^ 66; if(count > 0 && count <= 3){ count--; system.out.println("您的试用次数还剩余" + count + "次"); bos = new bufferedoutputstream(new fileoutputstream("src" + file.separator + "com" + file.separator + "monkey1024" + file.separator + "exercise" + file.separator + "config.txt")); //做加密处理 bos.write(count ^ 66); bos.flush(); }else{ system.out.println("您的试用次数已超出限制,请购买正版软件!"); } } catch (filenotfoundexception e) { e.printstacktrace(); } catch (ioexception e) { e.printstacktrace(); } finally{ try { //避免出现空指针 if(bis != null){ bis.close(); } if(bos != null){ bos.close(); } } catch (ioexception e) { e.printstacktrace(); } } } //试用次数加密处理 private static void code() { bufferedoutputstream bos = null; try { bos = new bufferedoutputstream(new fileoutputstream("src" + file.separator + "com" + file.separator + "monkey1024" + file.separator + "exercise" + file.separator + "config.txt")); //加密处理 bos.write(3 ^ 66); bos.flush(); } catch (filenotfoundexception e) { e.printstacktrace(); } catch (ioexception e) { e.printstacktrace(); } finally{ try { //避免出现空指针异常 if(bos != null){ bos.close(); } } catch (ioexception e) { e.printstacktrace(); } } }}
package com.wpbxx.exercise;import java.io.file;/** * 问题:统计项目根目录下以.txt结尾的文件数量,并将文件名打印出来 * 分析:获取项目根目录下的文件名 * 对文件名进行判断是否是以.txt结尾 */public class findtxt { public static void main(string[] args) { file file = new file("f:\\wpbxx\\01-javase\\代码\\code\\chapter-08"); file[] filearray = file.listfiles(); //返回一个file列表就是该目录下的file列表 //统计出现次数 int count = 0; for(file name : filearray){ string s = name.tostring(); //判断是否是以.txt文件结尾 if(s.endswith(".txt")){ if(name.isfile()){ count++; system.out.println(name); } } } system.out.println("以.txt文件结尾的数量是" + count + "个"); }}
package com.monkey1024.file;import java.io.file;import java.io.filenamefilter;/** * 问题:统计项目根目录下以.txt结尾的文件数量,并将文件名打印出来 * 使用文件过滤器实现上述需求 */public class filenamefiltertest01 { public static void main(string[] args) { file file = new file("f:\\monkey1024\\01-javase\\代码\\code\\chapter-08"); string[] namearray = file.list(new filenamefilter() { @override public boolean accept(file dir, string name){ //获取根目录下每个文件的file对象 file file1 = new file(dir, name); //编写筛选条件 return file1.isfile() && file1.getname().endswith(".txt"); } }); system.out.println("以.txt结尾的文件个数是" + namearray.length + "个"); for(string name : namearray){ system.out.println(name); } }}
package com.wpbxx.file;import java.io.file;import java.io.filenamefilter;/** * 问题:统计项目根目录下以.txt结尾的文件数量,并将文件名打印出来 * 使用文件过滤器实现上述需求 */public class filenamefiltertest01 { public static void main(string[] args) { file file = new file("f:\\wpbxx\\01-javase\\代码\\code\\chapter-08"); string[] namearray = file.list(new filenamefilter() {//重写accept方法 @override public boolean accept(file dir, string name){//将过滤的规则写进来 //获取根目录下每个文件的file对象 file file1 = new file(dir, name); //编写筛选条件 return file1.isfile() && file1.getname().endswith(".txt"); } }); system.out.println("以.txt结尾的文件个数是" + namearray.length + "个"); for(string name : namearray){ system.out.println(name); } }}
对对象的读取
为啥要对对象读取?
平时我们在java内存中的对象,是无 法进行io操作或者网络通信的,因为在进行io操作或者网络通信的时候,人家根本不知道内存中的对象是个什么东西,因此必须将对象以某种方式表示出来,即 存储对象中的状态。一个java对象的表示有各种各样的方式,java本身也提供给了用户一种表示对象的方式,那就是序列化。换句话说,序列化只是表示对 象的一种方式而已。ok,有了序列化,那么必然有反序列化,我们先看一下序列化、反序列化是什么意思。
序列化:将一个对象转换成一串二进制表示的字节数组,通过保存或转移这些字节数据来达到持久化的目的。
反序列化:将字节数组重新构造成对象。
序列化只需要实现java.io.serializable接口就可以了。序列化的时候有一个serialversionuid参数,java序列化机制是通过在运行时判断类的serialversionuid来验证版本一致性的。 在进行反序列化,java虚拟机会把传过来的字节流中的serialversionuid和本地相应实体类的serialversionuid进行比较, 如果相同就认为是一致的实体类,可以进行反序列化,否则java虚拟机会拒绝对这个实体类进行反序列化并抛出异常。serialversionuid有两 种生成方式:
如果一个类的对象支持序列化和反序列化,需要实现serializable,serializable中没有任何方法,只是相当于一个标记
有一个类
package com.monkey1024.serializable;import java.io.serializable;/** * 如果一个类的对象支持序列化和反序列化,需要实现serializable * serializable中没有任何方法 */public class student implements serializable{ /** * 自动生成序列化版本号 */ private static final long serialversionuid = -716323668524282676l; private string name; //添加属性后,使用反序列化时会报出invalidclassexception //transient修饰的变量不会被序列化 transient private int age; private boolean sex; public boolean issex() { return sex; } public void setsex(boolean sex) { this.sex = sex; } public int getage() { return age; } public void setage(int age) { this.age = age; } public string getname() { return name; } public void setname(string name) { this.name = name; } }
然后我们对这个类进行序列化和反序列化
student zhangsan = new student(); zhangsan.setname("张三"); zhangsan.setage(20); //写 objectoutputstream oos = new objectoutputstream(new fileoutputstream("zhangsan")); oos.writeobject(zhangsan); oos.flush(); //读 objectinputstream ois = new objectinputstream(new fileinputstream("zhangsan")); student s = (student)ois.readobject(); system.out.println(s.getname()); system.out.println(s.getage());
以上就是java中io流对文件操作的代码示例的详细内容。
该用户其它信息

VIP推荐

免费发布信息,免费发布B2B信息网站平台 - 三六零分类信息网 沪ICP备09012988号-2
企业名录 Product