Chapter01 流与文件(三) 文件操作

来源:互联网 发布:人工智能产品开发论文 编辑:程序博客网 时间:2024/06/10 10:54

Path是java 7中新添加的类,


Path的测试:

@Testpublic void testPath(){//通过连接字符串创建路径Path p=Paths.get("d:\\","path","1.txt");//得到路径d:\pathPath parent=p.getParent();System.out.println(parent.toString());//1.txtPath file=p.getFileName();System.out.println(file.toString());//根路径Path root=p.getRoot();System.out.println(root.toString());//由于参数是相对路径,返回d:\path\otherPath brother=p.resolveSibling("other");System.out.println(brother);//由于参数是绝对路径,返回brotherPath others=p.resolveSibling(brother);System.out.println(others);//参数是相对路径,返回d:\path1Path path1=root.resolve("path1");System.out.println(path1);//转化为FileFile realFile=p.toFile();}
path的一些方法:

文件的基本测试:

@Testpublic void testFiles() throws IOException{File file=new File("src"+File.separator+"1.txt");Path path=file.toPath();//读取文件的内容byte[] bytes=Files.readAllBytes(path);//将文件内容作为字符串读出,指定字符集String content=new String(bytes,"utf-8");System.out.println(content);//作为行的序列读出List<String> data=Files.readAllLines(path, Charset.forName("utf-8"));for (String string : data) {System.out.println(string);}//写内容的文件中,这会覆盖原来的内容Files.write(path, "这是写的入内容".getBytes());//如果是追加文本Files.write(path, "第二次写入的内容".getBytes(), StandardOpenOption.APPEND);//写入集合,任何现实了 Iterable的集合都可以List<String> lines=new ArrayList<String>();lines.add("Hello");lines.add("写入集合");lines.add("world");Files.write(path, lines, Charset.forName("utf-8"), StandardOpenOption.APPEND);//处理较大的文件必须使用流来处理byte[] b=new byte[256];InputStream in=Files.newInputStream(path);in.read(b);content=new String(b);in.close();System.out.println("使用流读取文件内容:"+content);//System.out.println(path.toAbsolutePath());//构建输出流OutputStream outputStream=Files.newOutputStream(path);//创建目录,创建的目录为testPath direct=Files.createDirectory(path.getParent().resolveSibling("test"));//创建文件Files.createFile(direct.resolve("3.txt"));//移动文件//System.out.println(path.toAbsolutePath().getRoot().resolve("test"));Files.copy(path,path.toAbsolutePath().getRoot().resolve("test"),StandardCopyOption.REPLACE_EXISTING);//删除文件,也就通过delete方法,不过文件不存在抛出异常Files.deleteIfExists(path);/** * //复习Path类Path other=path.resolveSibling("2.txt");File file2=other.toFile();FileOutputStream fileOutputStream=new FileOutputStream(file2);fileOutputStream.write("HelloWrold".getBytes());fileOutputStream.close(); */}

如果需要创建临时文件:

文件的一些属性:

文件属性的测试:

@Testpublic void testFiles2() throws IOException{File file=new File("src"+File.separator+"2.zip");Path path=file.toPath();//文件的字节大小long size=Files.size(path);System.out.println("2.zip的大小是:"+size+"byte");//返回文件的所有者System.out.println(Files.getOwner(path));//返回文件的属性BasicFileAttributes attributes=Files.readAttributes(path,BasicFileAttributes.class);//创建时间System.out.println(attributes.creationTime());//是否是目录System.out.println(attributes.isDirectory());//最后访问时间System.out.println(attributes.lastAccessTime());//最后修改时间System.out.println(attributes.lastModifiedTime());}

测试特定目录:

File file=new File("src"+File.separator+"1.zip");Path path=file.toPath();//获取所有的zip文件的路径try(DirectoryStream<Path> entries=Files.newDirectoryStream(path.getParent(),"*.zip")){for (Path path2 : entries) {System.out.println(path2);}}
过滤条件:


访问一个目录的所有子孙:


Files.walkFileTree(path.getParent(),new SimpleFileVisitor<Path>(){public FileVisitResult visitFile(Path path,BasicFileAttributes attributes){if(attributes.isDirectory()){System.out.println(path);}//表示有错误也继续访问return FileVisitResult.CONTINUE;}public FileVisitResult VisitFileFailed(Path path,IOException e){return FileVisitResult.CONTINUE;}});
对于zip文件系统,创建一个系统,有利于所有文件的管理:

@Testpublic void testZipSystem() throws IOException{//建立一个zip文件系统,文件的名字为zipnameFileSystem fs=FileSystems.newFileSystem(Paths.get("zipname"),null);//访问该文件系统的所有目录Files.walkFileTree(fs.getPath("/"), new SimpleFileVisitor<Path>(){public FileVisitResult visitFile(Path path,BasicFileAttributes attributes){if(attributes.isDirectory()){System.out.println(path);}//表示有错误也继续访问return FileVisitResult.CONTINUE;}});}
内存映射文件:

大多数操作系统可以将文件映射成为内存的一部分,可以实现文件的高效随机访问。

文件映射到内存的模式:


@Testpublic void testChannel() throws IOException{File file=new File("src"+File.separator+"2.txt");Path path=file.toPath();//采用追加模式获取channelFileChannel channel=FileChannel.open(path,StandardOpenOption.APPEND);//获取一个ByteBuffer,支持随机访问ByteBuffer buffer=channel.map(FileChannel.MapMode.READ_WRITE, 0, Files.size(path));//while(buffer.hasRemaining()){//doSomething}}
ByteBuffer的使用:

由于当多个程序操作文件时,文件有可能损坏,所以需要给文件加锁。


文件加锁注意事项:





原创粉丝点击