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

Path是java 7中新添加的类,


Path的测试:

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

文件的基本测试:

@Test
	public 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);
		//创建目录,创建的目录为test
		Path 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();
		 */
	
	}

如果需要创建临时文件:

文件的一些属性:

文件属性的测试:

@Test
	public 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文件系统,创建一个系统,有利于所有文件的管理:

	@Test
	public void testZipSystem() throws IOException
	{
		//建立一个zip文件系统,文件的名字为zipname
		FileSystem 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;
			}
		});
	}
内存映射文件:

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

文件映射到内存的模式:


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

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


文件加锁注意事项:





  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值