孙鑫JAVA学习笔记7-8.docVIP

  • 0
  • 0
  • 约2.9万字
  • 约 25页
  • 2018-02-21 发布于河南
  • 举报
孙鑫JAVA学习笔记7-8

七. I/O操作,字节流,字符流,字符集编码 1.I/O操作 是放在java.io包中的; 2.File类 一个File类的对象,表示了磁盘上的文件或目录。 File类提供了与平台无关的方法来对磁盘上的文件或目录进行操作。 import java.io.*; class FileTest { public static void main(String[] args) throws Exception //IO操作会经常抛出异常,我们交给JVM来处理 { //File f=new File(1.txt); // f.createNewFile(); //创建一个文件1.txt //f.mkdir(); //创建一个目录:1.txt /*指定绝对路径:\在JAVA是特殊的转义字符;所以输出\用“\\” */ //File f=new File(E:\\JavaLesson\\Lesson7\\1.txt); //--但它只能在当前windows系统有效;在Linux下无效 File fDir = new File(File.separator); //定义父目录为根目录;在windows下表示当前运行盘符的根目录! String strFile=JavaLesson+File.separator+ Lesson7+File.separator+1.txt; //win和Linux系统中编译成不同符合; File f = new File(fDir,strFile); //根目录+当前目录和文件;可移植到Linux; f.createNewFile(); } } 属性和方法: a.separator separator属性用来代表路径斜杠;通用的! 构造函数可以采用父目录+子文件名的方式: File(File parent, String child) Creates a new File instance from a parent abstract pathname and a child pathname string. b.删除文件:delete() boolean delete() Deletes the file or directory denoted by this abstract pathname. f.delete() //将f文件删除 c.deleteOnExit deleteOnExit(); 在程序退出的时候删除文件! 可以用来删除垃圾文件;临时文件等; d.createTempFile 创建临时文件到临时目录(返回File对象); static File createTempFile(String prefix, String suffix) Creates an empty file in the default temporary-file directory, using the given prefix and suffix to generate its name. e.g.: for(int i=0;i5;i++) { File f = File.createTempFile(winsun,.tmp); //会创建到系统默认的临时文件夹中; f.deleteOnExit(); //必须手动删除 } Thread.sleep(3000); e.List()方法: String[] list() ---返回字符串数组; 列出所有文件和子目录; Returns an array of strings naming the files and directories in the directory denoted by this abstract pathname. e.g.: File fDir=new File(File.separator); String strFile=JavaLesson+File.separator+Lesson6; File f=new File(fDir,strFile); String[] names=f.list(); //返回一个数组 for(int i=0;inames.length;i++)

文档评论(0)

1亿VIP精品文档

相关文档