写文件:追加模式写入
在构造时第2个参数置为true,表示append
运行结果如下:
在构造时第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();
}
}
}
运行结果如下: