使用的包
FileInputStream
FileOutputStream
File
代码部分
read()部分
package work;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
public class read {
public static void main(String[] args) {
// TODO Auto-generated method stub
//新建到E盘,名为temp
File f=new File("E:/temp");
//创建文件夹temp mkdirs可以创建多级文件夹
f.mkdirs();
File file=new File(f,"sample.txt");
//这里我们使用byte数组进行操作
byte[] data=new byte[100];
FileInputStream fis;
try {
//将需要读的对象file传给fis进行读取
fis = new FileInputStream(file);
try {
int n=fis.read(data);
//关闭流
fis.close();
System.out.println("写入"+n+"字节");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
write()部分
package work;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
public class write {
public static void main(String[] args) {
// TODO Auto-generated method stub
File f=new File("E:/temp");
f.mkdirs();
File file=new File(f,"sample.txt");
byte[] data={1,2,3,4};
try {
FileOutputStream fos=new FileOutputStream(file);
try {
fos.write(data,0,4);
fos.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("写入成功");
}
}