目录
- FileInputStream/FileOutputStream
--4.1 FileOutputStream文件输出流
--4.2 FileInputStream文件输入流
--4.3 使用FileInputStream和FileOutputStream进行拷贝
4.FileInputStream/FileOutputStream
4.1 FileOutputStream文件输出流
1.FileOutputStream常用构造方法
public FileOutputStream(File file)
public FileOutputStream(File file, boolean append) //append为true则会在原来文件的基础上写,而不会覆盖。
2.重要方法
void write(byte[] b)
void write(byte[] b, int off, int len)
void write(int b)
3.使用FileOutputStream写文件
File sdCardDir = Environment.getExternalStorageDirectory();//获取SDCard目录
File saveFile = new File(sdCardDir, "a.txt");
FileOutputStream outStream = null;
try{
outStream = new FileOutputStream(saveFile);
outStream.write("test".getBytes());
}catch (Exception e) {
e.printStackTrace();
}finally {
if(outStream!=null){
outStream.close();
}
}
4.2 FileInputStream文件输入流
- FileInputStream常用构造方法
public FileInputStream(String name)
public FileInputStream(File file)
2.重要方法
public int read() //返回读取的下一个字节 如果没有返回-1
public int read(byte b[]) //返回读取的总字节数,没有返回-1
public int read(byte b[], int off, int len) //返回读取的总字节数,没有返回-1
3.使用FileInputStream读文件
File sdCardDir = Environment.getExternalStorageDirectory();//获取SDCard目录
File saveFile = new File(sdCardDir, "a.txt");
FileInputStream fis = null;
try {
fis = new FileInputStream(saveFile);
byte[] buffer = new byte[1024];
int len = -1;
StringBuilder sb = new StringBuilder();
while ((len = fis.read(buffer)) != -1) {
sb.append(new String(buffer,0,len));
}
Log.d("xl", sb.toString());
} catch (Exception e) {
e.printStackTrace();
}finally {
if(fis!=null){
fis.close();
}
}
4.3 使用FileInputStream和FileOutputStream进行拷贝
File dir = Environment.getExternalStorageDirectory();
File file = new File(dir, "abc.txt");
File dst = new File(dir, "dst.text");
//进行拷贝
FileInputStream fis = new FileInputStream(file);
FileOutputStream fos = new FileOutputStream(dst);
int len = -1;
byte[] buffer = new byte[1024];
while ((len = fis.read(buffer)) != -1) {
fos.write(buffer, 0, len);
}
fis.close();
fos.close();