I/O流的一些知识

1创建文件

 File ff=new File("1.txt");//创建文件

 ff.createNewFile();
 
 
 File f2=new File("sss");
 ff.mkdir();//创建单个文件夹
 
 File f3=new File("sss/sss/sss");

 f3.mkdirs();//创建多重文件夹



2文件字节流FileInputStream类与FileOutputStream类


File file= new File("C:/test/word1.txt");
FileOutputStream out=null;
try {
out=new FileOutputStream(file,false);//文件输出流file后加true 则在文件末尾添加内容
                                     //加false  则替换文件内容
String str="天王盖地虎,玉帝日王母";
byte brr[]=str.getBytes();
out.write(brr);

} catch (FileNotFoundException e) {

e.printStackTrace();
} catch (IOException e) {

e.printStackTrace();
}
finally {
if(out!=null) {
try {
out.close();
} catch (IOException e) {

e.printStackTrace();
}
}
}


//  输入流


FileInputStream in=null;
try {
in =new FileInputStream(file);//输入流读文件
byte brr2[]=new byte[111];//缓冲区
int a=in.read(brr2);//读入缓冲区的总字节数
System.out.println("文件中的数据为:"+new String(brr2,0,a));//去掉空格


} catch (FileNotFoundException e) {

e.printStackTrace();
} catch (IOException e) {

e.printStackTrace();
}


3.文件字符流FileReader类与FileWriter类


File file= new File("C:/test/word5.txt");
FileWriter out=null;
try {
out=new FileWriter(file);//字符输出流file后加true 则在文件末尾添加内容
                                     //加false  则替换文件内容
String str="宝塔镇河妖,段友吊缠腰";

out.write(str);//将字符串写入文本文档

} catch (FileNotFoundException e) {

e.printStackTrace();
} catch (IOException e) {

e.printStackTrace();
}
finally {
if(out!=null) {
try {
out.close();
} catch (IOException e) {

e.printStackTrace();
}
}
}


// 字符 输入流


FileReader in=null;
try {
in =new FileReader(file);//输入流读文件
char[] ch=new char[1024];//缓冲区
int count   ;             //已经读出的字符数
while((count=in.read(ch))!=-1) {//循环读出文档中的数据   知道所有字符都读完
System.out.println("文件中的数据为:"+new String(ch,0,count));
}


} catch (FileNotFoundException e) {

e.printStackTrace();
} catch (IOException e) {

e.printStackTrace();
}











猜你喜欢

转载自blog.csdn.net/qzy623569881/article/details/80088550