黑马程序员——Java基础---IO(二)
来源:互联网 发布:jre windows i586.exe 编辑:程序博客网 时间:2024/05/16 08:05
------Java培训、Android培训、iOS培训、.Net培训、期待与您交流! -------
1.File类
1.概述
1.用来将文件或者文件夹封装成对象。方便对文件与文件夹属性信息进行操作。File对象可以作为参数传递给
构造函数,了解File类中的常用方法。
2.目录分隔符:File.separator 代替 \\, 是为了跨平台性而代替的一个属性。
2.常用方法
1.创建
boolean createNewFile( );
在指定位置创建文件,如果文件已经存在则不创建。不同于输出流会覆盖。
static File createTempFile( );
创建临时目录,只要给出前缀后缀即可。
boolean mkdir( ): 创建此抽象路径名指定的目录。mkdirs( )创建多级目录
package com.blog.part4.IO流;import java.io.*;public class CreateDemo {public static void main(String[] args) throws IOException{// 在指定位置创建文件 File f=new File("D:/ga.text"); Boolean b=f.createNewFile(); //创建临时文件,直接调用静态方法File.createTempFile("aasss", "zx");//创建单级目录可以用mkdir,多级目录可以用mkdirsFile f2= new File("D:/a/b/c");System.out.println(f2.mkdirs());}}
2.获取
String getName() 文件或者路径的名称。
String getPath( ) 抽象路径名。
String getParent( ) 该方法返回的是绝对路径下的父目录,如果相对路径则返回。
示例:
package com.blog.part4.IO流;import java.io.*;public class CreateDemo {public static void main(String[] args) throws IOException{// 在指定位置创建文件 File f=new File("D:/a/b/c"); sop(f.getName()); sop(f.getPath()); sop(f.getParentFile());}public static void sop(Object obj){System.out.println(obj);}}运行结果:
String getAbsoluteFile( ) // File getAbsolutePath( )
long lastModified();最后一次修改的时间
long length() 文件的长度
示例:
package com.blog.part4.IO流;import java.io.*;public class CreateDemo {public static void main(String[] args) throws IOException{// 在指定位置创建文件 File f=new File("D:/a/b/c/d.txt"); sop(f.getAbsoluteFile()); sop(f.lastModified()); sop(f.length());}public static void sop(Object obj){System.out.println(obj);}}运行结果;
3.判断
boolean canExecute();//是否是可执行文件
boolean exists();//文件是否存在
boolean isFile();//是否是文件
boolean isDirectory();//是否是文件夹
boolean isHidden();//是否是隐藏文件
boolean isAbsolute();//文件是否是绝对路径
4.删除
boolean delete();
//删除文件或目录。文件存在,返回true;文件不存在或者正在被执行,返回false。
void deleteOnExit();//在程序退出时删除指定文件
5.文件列表
static File[] listRoots();//列出可用的文件系统根目录
FilenameFilter:文件名过滤器,是一个接口,其中包含一个方法,accept(Filedir,String name),返回的是boolean型,
对不符合条件的文件过滤掉。
String[] list();/列出当前目录下所有文件,包括隐藏。调用list方法的file对象必须是封装了一个目录。该目录还必须存在。
String[]list(FilenameFilter filter); //返回一个字符串数组,获取目录中满足指定过滤器的文件或目录。
File[] listFiles();//返回一个抽象路径名数组,获取当前文件夹下的所有文件和文件夹,可以进行进一步操作
File[] ListFiles(FilenameFilterfilter);//返回抽象路径名数组,获取目录中满足指定过滤器的文件或目录。
/** * 需求:练习使用list、listFiles和文件过滤器 * @author jinlong * */package com.blog.part4.IO流;import java.io.*;public class FileListDemo {public static void main(String[] args) { File f=new File("D:/javatest"); //系统根目录 sop("-------系统根目录----------"); sopPrint(File.listRoots()); sop("---------指定目录--------"); String[] sarr=f.list(); sopPrint(sarr); sop("---------指定目录过滤--------"); getJava(f); sop("---------删除第一个目录-------"); File[] f1=f.listFiles(); sop( f1[0].delete());}//获取目录下所有.java文件public static void getJava(File f){//定义过滤器,因为过滤器是接口类型,此处可以传入匿名内部类子对象String [] javaFile=f.list(new FilenameFilter(){//复写accept方法 public boolean accept(File f,String name) { return name.endsWith(".java");//判断文件名是不是以.java结尾 }});sopPrint(javaFile);}//打印数组,利用泛型public static <T> void sopPrint(T[] tarr){for(T t:tarr)sop(t);}//打印语句public static void sop(Object obj){System.out.println(obj);}}
3.递归
1.定义
当函数内每一次循环还可以调用本功能来实现,也就是函数自身调用自身。这种表现形式,或者编程手法,称为递归。
2.条件
a、限定条件。是来结束循环调用,否则是死循环。
b、注意递归的次数,尽量避免内存溢出。因为每次调用自身的时候都会先执行下一次调用自己的方法,所以会不断在栈内存中开辟新空间,次数 过多,会导致内存溢出。
/** * 需求:输出指定目录下所有内容列表(包含在子目录中内容),可以理解为深度遍历 * 思路:对于第一层级目录可以直接调用方法打印输出,当它有子目录时,其实也是调用同样方法输出 * 对于不同层级目录只需做个判断操作,然后调用同样方法,所以可以用递归。 * 这个作为判断的条件可以用isDirectory * */package com.blog.part4.IO流;import java.io.*;public class FileListsDemo { public static void main(String[]args) { File f=new File("D:/Users/exam"); getFileLists(f); } public static void getFileLists(File f) { File[] fs=f.listFiles(); for(int x=0;x<fs.length;x++) { if(fs[x].isDirectory()) getFileLists(fs[x]);//调用函数自身 System.out.println("文件名:"+fs[x].getAbsolutePath()); } }}
/** * 需求:利用递归求二进制 * @author jinlong * */package com.blog.part4.IO流;public class toBinDemo { public static void main(String[]args) { toBin(6); } //方法 public static void toBin(int a) { if(a>0) { toBin(a/2); System.out.print(a%2); } }}
示例三:
/** * 需求:删除一个指定目录下所有内容 * 思路:删除一个目录要从内向外删除,即如果一个文件夹有内容不能被删除的 * 所以类似上边的深度遍历,可以用递归将每个遍历到的文件删除 * @author jinlong * */package com.blog.part4.IO流;import java.io.File;public class DelFilesDemo {public static void main(String[] args) {// 定义指定目录,调用方法File f = new File("D:/a");delFiles(f);}public static void delFiles(File f){File [] fs=f.listFiles();for(int x=0;x<fs.length;x++){ if(fs[x].isDirectory()) delFiles(fs[x]);//递归 fs[x].delete();}}}
示例四:
/** * 需求:将一个指定目录下的java文件的绝对路径,存储到一个文本文件中。建立一个java文件列表的文件。 * 思路: 1、对指定的目录进行递归。 2、获取递归过程所有的java文件的路径。 3、将这些路径存储到集合中。 4、将集合中的数据写入到一个文件中。 * @author jinlong * */package com.blog.part4.IO流;import java.io.*;import java.util.*;public class CopyFilesDemo {// String s=null;public static void main(String[] args){List<File>list=new ArrayList<File>();//定义一个存储数据的集合//指定起始源目录和地址目录File start=new File("D:/Program Files (x86)");File end=new File("E:/a.txt");//调用读取和写入放啊copyFiles(start,list);writeToFile(list,end);}//将指定目录下所有文件路径写入集合public static void copyFiles(File f,List<File> list) {File[] fs=f.listFiles();for(int x=0;x<fs.length;x++){if(fs[x].isDirectory())//判断是否是目录{list.add(fs[x].getAbsoluteFile());//存入父目录copyFiles(fs[x],list);}list.add(fs[x]);}}//将集合写入目标文本文件public static void writeToFile(List<File>list,File f){BufferedWriter bw=null;try {bw=new BufferedWriter(new FileWriter(f)); for(File fn:list){ bw.write(fn.getAbsolutePath()); bw.newLine();//换行 bw.flush();//刷新}} catch (IOException e){// TODO Auto-generated catch blockthrow new RuntimeException("写入文件失败"); }finally{try {if(bw!=null)bw.close();} catch (IOException e) {// TODO Auto-generated catch blockthrow new RuntimeException("流资源关闭失败"); }}}}
2.Properties类
1.概述
1.Properties是Hashtable的子类,它具备Map集合的特点。而且它里面还有存储的键值对,都是字符串,无泛型定义。是集合中和IO技术想 结合的集合容器。
2.特点:
1)可用于键值对形式的配置文件
2)在加载时,需要数据有固定的格式,常用的是:键=值
2.特有方法
1、设置
Object setProperty(String key,String value);
//设置键和值,调用Hashtable的方法put
2、获取
String getProperty(String key);
//指定key搜索value
Set<String> stringPropertyName();
//返回属性列表的键集,存入Set集合
3、加载流和存入流
void load(InputStream ism);
//从输入字节流中读取属性列表(键和元素对)。又称将流中的数据加载进集合。
void load(Reader reader);
//从输入字符流中读取属性列表(键和元素对)。又称将流中的数据加载进集合。
void list(PrintStream out);//将属性列表输出到指定的输出流
void store(OutputStream out,String comments);
//对应load(InputStream )将属性列表(键值对)写入输出流。comments属性列表的描述。
void store(Writer writer, String comments);
//对应load(Reader)将属性列表(键值对)写入输出流。comments属性列表的描述。
import java.util.Properties;import java.util.Set;public class PropertiesDemo{ public static void main(String[] args){ propertiesDemo(); } public static void propertiesDemo(){ //创建一个Properties集合 Properties prop = new Properties(); //存储元素 prop.setProperty( "zhangsan","10" ); prop.setProperty( "lisi","20" ); prop.setProperty( "wangwu","30" ); prop.setProperty( "zhaoliu","40" ); //修改元素 prop.setProperty( "wangwu","26" ); //取出所有元素 Set<String> names = prop.stringPropertyNames(); for(String name : names){ String value = prop.getProperty(name); System.out.println(name + ":" + value); } }}
/*与流对象结合使用*/import java.util.Properties;public class PropertiesDemo{ public static void main(String[] args){ propertiesDemo(); } public static void propertiesDemo(){ Properties prop = new Properties(); prop.setProperty( "zhangsan","10" ); prop.setProperty( "lisi","20" ); prop.setProperty( "wangwu","30" ); prop.setProperty( "zhaoliu","40" ); prop.list(System.out);//从控制台打印 }}
package com.blog.part4.IO流;import java.io.*;import java.util.Properties;public class PropertiesDemo{ public static void main(String[] args) throws Exception { propertiesDemo(); } public static void propertiesDemo() throws Exception { Properties prop = new Properties(); prop.setProperty( "zhangsan","10" ); prop.setProperty( "lisi","20" ); prop.setProperty( "wangwu","30" ); prop.setProperty( "zhaoliu","40" ); //想要将这些集合中的字符串键值信息持久化存储到文件中 /*字符流 * FileWriter fw=new FileWriter("D:/info.txt"); * prop.store(fw, "name+age"); * fw.close(); * */ /* 存储到xml文件中 * FileOutputStream fos = new FileOutputStream("info.xml" ); prop.storeToXML(fos, "name+age"); */ FileOutputStream fos = new FileOutputStream("info.txt" ); prop.store(fos, "name+age"); fos.close(); }}
//读取配置文件中的键值对,修改键值对package com.blog.part4.IO流;import java.io.*;import java.util.*;public class PropertiesLoadDemo {public static void main(String[] args) throws InvalidPropertiesFormatException, IOException{ //读取键值对 proPrint();//修改配置文件 proChange("lisi","100"); proPrint();}public static void proPrint() throws InvalidPropertiesFormatException, IOException{Properties prop=new Properties();//需要读取流 FileInputStream fis =new FileInputStream("info.xml"); //使用load方法 prop.loadFromXML(fis); prop.list(System.out); }public static void proChange(String key,String value) throws InvalidPropertiesFormatException, IOException{FileInputStream fis =new FileInputStream("info.xml");Properties prop=new Properties();prop.loadFromXML(fis);prop.setProperty(key, value);FileOutputStream fos =new FileOutputStream("info.xml");prop.storeToXML(fos,"");}}
运行结果:
/** * 需求 :获取一个应用程序运行的次数,如果超过5次,给出使用次数已到请注册的提示,并不要再运行程序。 * 思路:我们需要记录一个程序的运行次数,可以定义一个计数器。 * 这个计数器存储的位置值得思考:程序启动时计数,程序结束时不能消失。每次启动程序要使用同一个计数器。 * 所以可以将程序使用次数存储到Properties中,程序运行之前进行判断 * 这个功能其实设计就是程序都有的配置文件,每个程序运行之前都要先加载自身的配置文件获取配置信息 * */package com.blog.part4.IO流;import java.io.*;import java.util.*;public class RegistDemo {public static void main(String[] args) throws IOException {// TODO Auto-generated method stubgetAppCount();}public static void getAppCount() throws IOException{ //定义Properties对象Properties p=new Properties();//获取配置文件File conf=new File("Count.properties");if(!conf.exists()){conf.createNewFile();}FileInputStream fis=new FileInputStream(conf);p.load(fis);//从集合中获取使用次数String value=p.getProperty("time");//定义计数器,记录获取到的此时int count=0;if( value!=null){count=Integer.parseInt(value); if(count>=5) { throw new RuntimeException("超过使用次数,请付费"); }}System.out.println("已经使用了:"+(++count)+"次");//将改变后的次数重新存储到配置文件中p.setProperty("time", count+"");//FileOutputStream fos=new FileOutputStream(conf);p.store(fos, "time+count");fos.close();fis.close();}}
运行结果:
3.打印流
1、概述
1、打印流包括:PrintStream和PrintWriter
2、该流提供了打印方法,可将各种类型的数据都原样打印。
2、字节打印流:PrintStream(永远不会抛IO异常)
构造方法中可接收的参数类型:
1、File对象。File
2、字符串路径:String
3、字符输出流:OutputStream
import java.io.PrintStream;public class PrintStreamDemo{ public static void main(String[] args) throws Exception { PrintStream out = new PrintStream("print.txt" ); //write(int b)方法只写最低8位 out.write(97); //a //print方法将97先变成字符串保持原样将数据打印到目的地 out.print(97); //97 out.close(); }}
3、字符串打印流:PrintWriter
构造方法中可接受的参数类型
1、File对象:File
2、字符串路径:String
3、字节输出流:OutputStream
4、字符输出流:Writer
示例;import java.io.*;class PrintStreamDemo{public static void main(String[] args) throws IOException{//键盘录入BufferedReader bufr = new BufferedReader(new InputStreamReader(System.in));//打印流关联文件,自动刷新PrintWriter out = new PrintWriter(new FileWriter("a.txt"),true);String line = null;while((line=bufr.readLine())!=null){if("over".equals(line))//结束字符break;out.println(line.toUpperCase());//out.flush();}//关流out.close();bufr.close();}}
4.序列流
1、概述
1、SequenceInputStream对多个流进行合并。也被称为合并流。
2、常用构造函数
SequenceInputStream(Enumeration<?extends FileInputStream> e)
2、常见合并多个流文件步骤
1、创建集合,并将流对象添加进集合
2、创建Enumeration对象,将集合元素加入。
3、创建SequenceInputStream对象,合并流对象
4、创建写入流对象,FileOutputStream关联写入文件
5、利用SequenceInputStream对象和FileOutputStream对象读数据进行反复读写操作。
示例:/* * 需求:将1.txt、2.txt、3、txt文件中的数据合并到一个文件中。 * 思路:合并多个文件其实合并流的应用 * 将所有源文件的数据流存储到一个集合中,然后将集合元素加入Enumeration对象,使用SequenceInputStream * 将他变成一个流,然后输出到指定文件即可 * 将这个合并动作抽取出来,利用可变长参数可以写成合并任意数量文件的方法。 * * */package com.blog.part4.IO流;import java.io.*;import java.util.*;public class SeqInputDemo {public static void main(String[] args) throws IOException {// 定义三个源File f1=new File("D:/a.txt");File f2=new File("D:/b.txt");File f3=new File("D:/c.txt"); //合并a和b两个文件//addTxt(f1,f2);//合并a,b,c三个文件addTxt(f1,f2,f3);}public static void addTxt(File... f) throws IOException//可变长度参数{//定义集合存储获取到的流ArrayList<FileInputStream> al = new ArrayList<FileInputStream>();for(File f0:f) {al.add(new FileInputStream(f0));}//创建Enumeration对象Enumeration<FileInputStream> en = Collections.enumeration(al);//创建SequenceInputStream对象 SequenceInputStream sis = new SequenceInputStream(en); //写入到新文件seq.txt中 File temp=new File("D:/seq.txt"); if(temp.exists())//如果不存在时,创建seq文件 { temp.createNewFile(); } //利用数组输出 FileOutputStream fos = new FileOutputStream(temp); byte[] buf = new byte[1024]; int len=0; while((len=sis.read(buf))!=-1) { fos.write(buf, 0, len); } //关闭流 fos.close(); sis.close();}}
示例:
/** * 需求:1.先将mp3文件按照1M大小分割成几部分 * 2.合并这三个文件成为可执行文件 *思路: * @author jinlong * */package com.blog.part4.IO流;import java.io.*;import java.util.*;public class SepMp3 {public static void main(String[] args) throws IOException, InterruptedException {File f=new File("D:/追梦.mp3");//将追梦.mp3分解seqMp3(f);//看到结果分解了13份File f1=new File("D:/合并.MP3");//存储路径addMp3(f1,13);}//分割MP3public static void seqMp3(File file) throws IOException{//关联数据源BufferedInputStream bis=new BufferedInputStream(new FileInputStream(file)); BufferedOutputStream bos=null; byte[] buf=new byte[1024*1024]; //按照1M大小分割 int len=0,x=0; while ((len=bis.read(buf))!=-1) { //每满1M就写入一个新文件中 File f=new File("D:/"+(++x)+".mp3"); f.createNewFile(); bos=new BufferedOutputStream(new FileOutputStream(f)); bos.write(buf,0,len); bos.close();//每写完一个文件要记得关流 } //关流 bis.close(); }//合并mp3public static void addMp3(File f,int num) throws IOException//f表示目的路径,num表示文件个数{//定义集合存储获取到的流ArrayList<FileInputStream> al = new ArrayList<FileInputStream>();//将所有分文件连接数据源加入集合中 for (int x=1;x<=num ; x++) { al.add(new FileInputStream("D:/"+x+".mp3")); } //创建Enumeration对象Enumeration<FileInputStream> en = Collections.enumeration(al);//创建SequenceInputStream对象 SequenceInputStream sis = new SequenceInputStream(en); //写入到新文件seq.mp3中 File temp=new File(f.getAbsolutePath()); if(temp.exists())//如果不存在时,创建seq文件 { temp.createNewFile(); } //利用数组输出 FileOutputStream fos = new FileOutputStream(temp); byte[] buf = new byte[1024]; int len=0; while((len=sis.read(buf))!=-1) { fos.write(buf, 0, len); } //关闭流 fos.close(); sis.close();}}
- 黑马程序员——Java基础——IO(二)
- 黑马程序员——Java基础---IO流(二)
- 黑马程序员——java基础-IO(二)
- 黑马程序员——Java基础--IO流(二)
- 黑马程序员——Java基础--IO(二)
- 黑马程序员——Java基础---IO(二)
- 黑马程序员——Java基础--------IO流(二)
- 黑马程序员——JAVA基础----IO流(二)
- 黑马程序员--Java基础--10IO(二)
- 黑马程序员-----java基础IO流<二>
- 黑马程序员--------------JAVA基础-------------IO流二
- 黑马程序员-----Java基础-----IO流(二)
- 黑马程序员——Java基础---IO
- 黑马程序员——java基础--IO
- 黑马程序员——Java基础---IO
- 黑马程序员 Java基础——IO
- 黑马程序员—Java基础—IO
- 黑马程序员——————java基础之Io二
- HDU3395(最小费用流)
- Servlets - Environment Setup
- Servlets - Life Cycle
- LeetCode 题解(202) : Reverse Bits
- Servlets - Examples
- 黑马程序员——Java基础---IO(二)
- LeetCode Add Two Numbers
- 《C#入门经典(第6版)》读书笔记4_第四章:流程控制
- USACO 1.1 Milking Cows
- C语言的字符处理函数库
- Some projects cannot be imported because they already exist in the workspace
- 【LeetCode-面试算法经典-Java实现】【219-Contains Duplicate II(包含重复元素II)】
- 【LeetCode-面试算法经典-Java实现】【223-Rectangle Area(矩形区域)】
- 【LeetCode-面试算法经典-Java实现】【225-Implement Stack using Queues(用队列实现栈操作)】