Java高级语法笔记-文件读写

写文件:追加模式写入
在构造时第2个参数置为true,表示append

new FileOutputStream(filename, true);


使用FileInputStream可以从文件中读取数据
// 设置一个大的缓冲区
byte[] buf = new byte[1024];
// 打开文件,把数据读到缓冲区里
FileInputStream fin = new FileInputStream(filename);
count = fin.read(buf, 0, 1024);
fin.close();


代码如下:

package my;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.nio.ByteBuffer;

public class HelloWorld
{
	//写文件测试
	public static void test1() {
		byte[] data= {1,2,3,4,5,6};
		File filename=new File("c:/example/haha");
		try {
			FileOutputStream fout=new FileOutputStream(filename);
			fout.write(data);
			fout.close();
		}catch(IOException e) {
			e.printStackTrace();
		}
	}
	//指定数据偏移写入
	public static void test2() {
		byte[]data= {1,2,3,4,5,6};
		File filename=new File("c:/example/haha");
		try {
			FileOutputStream fout=new FileOutputStream(filename);
			fout.write(data, 1, 2);
			fout.close();
		}catch(IOException e) {
			e.printStackTrace();
		}
	}
	
	public static void write(byte[] data) {
		File filename=new File("c:/example/haha2");
		try {
			FileOutputStream fout=new FileOutputStream(filename);
			fout.write(data);
			fout.close();
		}catch(IOException e) {
			e.printStackTrace();
		}
	}
	
	public static int read(byte[] buf,String n) {
		int count=0;
		File filename=new File(n);
		try {
			FileInputStream fin=new FileInputStream(filename);
			count=fin.read(buf);
			fin.close();
		}catch(IOException e) {
			e.printStackTrace();
		}
		
		return count;
	}
	
	//读文件测试
	public static void test3() {
		byte[] buf=new byte[1024];
		int count=0;
		File filename=new File("c:/example/haha");
		try {
			FileInputStream fin=new FileInputStream(filename);
			count=fin.read(buf,0,1024);
			fin.close();
		}catch(IOException e) {
			e.printStackTrace();
		}
		System.out.println("test3:读取haha文件获取:"+count+"bytes");
	}

	public static void main(String[] args)
	{		
		//test1();
		//test2();
		//test3();
		String str="你好,中国!";
		try {
			byte[] data=str.getBytes("GBK");	
			write(data);
		}catch(UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		byte[] buf=new byte[1024];
		int n=read(buf,"c:/example/haha2");
		try {
			String strRead=new String(buf,0,n,"GBK");
			System.out.println("got:"+strRead);
		}catch(UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		
	}
}

运行结果如下:



评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

IT1995

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值