案例0
功能:1、创建文件夹、文件 2、遍历文件夹下面的所有文件
public class Test1 {
public static void main(String[] args) {
// TODO Auto-generated method stub
//创建新文件夹对象ff
File f1 = new File("D:/FF");
//如果存在
if(f1.isDirectory()){
System.out.println("已经存在该文件夹!");
//将文件夹下面的所有文件 组成数组
File lists[] = f1.listFiles();
System.out.println("ff文件夹下面有"+lists.length+"个文件");
//遍历,取出所有的文件名称
for(int i=0;i<lists.length;i++){
System.out.println("文件名 :" +lists[i].getName());
}
}else {
//如果不存在该文件夹,则输出
System.out.println("该文件夹不存在!");
f1.mkdir();
}
//在该文件夹下面创建 新的文件
File f2 = new File("d:\\ff\\psp.txt");
//如果存在在文件
if(f2.exists()){
System.out.println("已经存在该文件");
}else{
try {
f2.createNewFile();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
案例1
功能:从数据源中读取数据到内存(FileInputStream的使用)
/**
* 功能:从数据源中读取数据到内存
*/
public class Test {
public static void main(String[] args) {
// TODO Auto-generated method stub
File f1 = new File("d:\\ff\\test.txt");
FileInputStream fis=null;
try {
fis = new FileInputStream(f1);
byte[] bytes= new byte[1024];
//得到实际读取的长度
int n=0;
//循环读取
while((n=fis.read(bytes))!=-1){
String s = new String(bytes,0,n);
System.out.print(s);
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
//最后一定要关闭文件流
try {
fis.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
案例2
功能:演示FileOutputStream,从内存中读取数据到数据源
public class Test {
public static void main(String[] args) {
// TODO Auto-generated method stub
File f1 = new File("d:\\ff\\test.txt");
FileOutputStream fos = null;
try {
fos = new FileOutputStream(f1);
String s="我是曾可达,我是曾可达!\r\n";
String s2="听到请回答!";
byte bytes[] = new byte[1024];
fos.write(s.getBytes());
fos.write(s2.getBytes());
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
try {
fos.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
案例3
功能:演示FileInputStream ,FileOutputStream ;将图片从C盘拷贝到D盘
public class Test {
public static void main(String[] args) {
//定义输入流
FileInputStream fis =null;
//定义输出流
FileOutputStream fos=null;
try {
fis = new FileInputStream("c:\\boy.jpg");
fos = new FileOutputStream("d:\\boy.jpg");
//读取
byte [] bytes = new byte[1024];
int n=0;
while((n=fis.read(bytes))!=-1){
fos.write(bytes, 0, n);
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
try {
fis.close();
fos.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
本文摘抄于《AndroidIO流读写文件》
© 版权声明