java读写文件用什么类_java读写文件类总结

一、读文件 String filename = "a.txt"; ①//以字节为单位读取文件内容,一次读取一个字节 File file = new File(fileNanme); InputStream in = new FileInputStream(file); int tempbyte; while( (tempbyte=in.read())!=-1 ){ System.out.write(tempbyte); } ②//以字节为单位读取文件内容,一次读取多个字节 byte[] tempbytes = new byte[100]; InputStream in = new FileInputStream(fileName); int byteread = 0; while( (byteread =in.read(tempbyte))!=-1 ){ System.out.write(tempbytes,0,byteread); } ③//以字符为单位读取文件内容,一次读取一个字符 File file = new File(fileNanme); Reader reader = new InputeStreamReader(new FileInputStream(file)); int tempchar=0; while( (tempchar = reader.read())!=-1 ){ System.out.print((char)tempchar); } ④//以字符为单位读取文件内容,一次读取多个字符 File file = new File(fileNanme); Reader reader = new InputeStreamReader(new FileInputStream(file)); char[] tempchars= new char[30]; int charread =0 ;//一次性读取的字符个数 while( (charread = reader.read(tempchars))!=-1 ){ } ⑤//以行为单位读取文件内容 File file = new File(fileNanme); BufferedReader reader = new BufferedReader(new FileReader(file)); String tempString = null; while( (tempString = reader.readLine())!=null ){ System.out.println(tempString); } ⑥//随即读取文件内容 RandomAccessFile randomFile = new RandomAccessFile(fileName,"r"); long fileLength = randomFile.length(); int beginIndex = (fileLength >4 ? 4:0); randomFile.seek(beginIndex); byte[] bytes = new byte[10]; int byteread = 0; while( (byteread = randomFile.read(bytes))!=1 ){ System.out.write(bytes,0,byteread); } 二、写文件 ①//以字节为单位写文件 File file = new File(fileNanme); OutputStream out = new FileOutputStream(file); String content = "abcdef"; byte[] bytes = content.getBytes(); out.write(bytes); ②//以字符为单位写文件 File file = new File(fileNanme); Writer writer= new OutpoutStreamWriter(new FileOutputStream(file)); String content = "abcdef"; writer.write(content); ③ //以行为单位写文件 File file = new File(fileNanme); PrintWriter writer = new PrintWriter(new FileOutputStream(file)); writer.println("文件内容:"); writer.print(155); writer.print(true); writer.print("abcd"); ④//添加容到文件末尾 String content = "abcdef"; FileWriter writer = new FileWriter(fileName,true);//如果为true则添加到文件末尾;如果为false,则将文件的内容清掉,再将内容添加到文件中 writer.write(content);

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值