java nio file_JAVA NIO File/Path操作

JAVA NIO 提供了一组新的对文件I/O的操作; 虽然使用起来很方便, 但是学习起来还是需要一些记忆成本; 就记录一下使用过的一些操作;

Path 是一个URI抽象的概念; 对于Path实例变量的命名,从我目前个人的经验, 我觉得Path对象的实例并不一定也要叫做Path; 可以根据Path到底代指的什么内容来命名,可以命名为xxxfile(代表文件), xxxfolder(代表文件夹)

//可以是一个具体的文件;

Path file = Paths.get("c://test.txt");

//可以是一个文件夹;

Path folder = Paths.get("c://myFolder");

//也可以是个目前尚不存在的一个资源定位;

Path notExisted = Paths.get("c://fefe131231231fe.txt");

//随便测试一下可以直接的协议;

//不支持, 还是用jsoup;

Path file = null;

try {

URI http= new URI("http://www.baidu.com");

file = Paths.get(http);

} catch (FileSystemNotFoundException e) {

System.out.println("do not support http");

}

//不支持可以考虑使用Channel;

try {

URI ftp= new URI("ftp:///");

file = Paths.get(ftp);

} catch (FileSystemNotFoundException e) {

System.out.println("do not support ftp");

}

//支持;

try {

URI ftp= new URI("file:///");

file = Paths.get(ftp);

} catch (FileSystemNotFoundException e) {

System.out.println("do not support ftp");

}

当获得Path以后, 可以先转变成File(toFile)再进一步判断它是否存在,它的类型,以及决定是否创建使用(Files)

curFile.toFile() == null; curFile.toFile().isDirectory(); !curFile.toFile().exists();

Files.createDirectories(curFile);

Files.createFile(curFile);

//直接用file创建文件夹似乎更方便?

curFiel.getParent().toFile().mrdirs();

可以使用Files工具,对Path所定位的文件以及文件夹设置访问权限;

//简单示例设置文件/文件夹为可编辑;

Files.setAttribute(newPath, "dos:readonly", false);

//复杂一点的代码示例,更优美点的写法, 并考虑到Linux 和 Windows下的兼容问题;

Path file = Paths.get("file.txt");

// Files.createFile(file);

System.out.println(Files.isWritable(file)); // true

// Query file system

FileStore fileStore = Files.getFileStore(file);

if (fileStore.supportsFileAttributeView(DosFileAttributeView.class)) {

DosFileAttributeView attrs =

Files.getFileAttributeView(

file, DosFileAttributeView.class);

attrs.setSystem(true);

attrs.setHidden(true);

attrs.setReadOnly(true);

} else if (fileStore.supportsFileAttributeView(PosixFileAttributeView.class)) {

// Change permissions

}

System.out.println(Files.isWritable(file)); // false

}

进行文件的复制移动操作;

//这里的curFile, tarPath均为Path的实例;

Files.copy(curFile, tarPath, StandardCopyOption.REPLACE_EXISTING);

Files.move(source, target,REPLACE_EXISTING,ATOMIC_MOVE);

//StandardCopyOption 有个属性ATOMIC_MOVE;

//An atomic file operation is an operation that cannot be interrupted or "partially" performed. Either the entire operation is performed or the operation fails. This is important when you have multiple processes operating on the same area of the file system, and you need to guarantee that each process accesses a complete file.

文件的复制和移动操作, 往往不仅仅是复制文件本身;而是希望可以可以将某个文件, 以及它相应的一段文件夹也复制, 那么Path之间的转化,以及如何生成一段相对路径就很有用;

//将文件 C://src//com.dominic//com//test.txt; 复制到c://src_old//com.dominic//com//test.txt下;

//虽然可以不用拼写一部分的相对路径的内容, 但是原生的工具书写起来仍旧有一些麻烦;可能有更好的写法,没进一步研究;

Path srcFile = Paths.get("c:src_old/com/dominic/www/hello.txt");

try {

if(!srcFile.toFile().exists()) {

srcFile.getParent().toFile().mkdirs();

Files.createFile(srcFile);

}

//com/dominic/www/hello.txt;

Path FileWithrelatePath = Paths.get("c:src_old/").relativize(srcFile);

//c:/src/com/dominic/www/hello.txt;

Path tarPath = Paths.get("c:/src").resolve(FileWithrelatePath);

tarPath.getParent().toFile().mkdirs();

Files.copy(srcFile, tarPath, StandardCopyOption.REPLACE_EXISTING);

} catch (IOException e) {

e.printStackTrace();

}

结合Files.walk, 以及Path.resolve, rellativize实现将文件从某个文件夹复制到另一个文件夹;

//将c:src_old 文件夹下的所有文件复制到c:src_new文件夹下;

Path oldPath = Paths.get("c:src_old");

Files.walk(oldPath).forEach(path -> {

Path relativePath = oldPath.relativize(path);

try {

Files.copy(path, Paths.get("c:src_new").resolve(relativePath), StandardCopyOption.REPLACE_EXISTING);

} catch (IOException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

});

通过Files 方法可以获得Path带缓冲的输入输出流;

zip文件的方法

public static void writeToFileZipFileContents(String zipFileName,

String outputFileName)

throws java.io.IOException {

java.nio.charset.Charset charset =

java.nio.charset.StandardCharsets.US_ASCII;

java.nio.file.Path outputFilePath =

java.nio.file.Paths.get(outputFileName);

// Open zip file and create output file with

// try-with-resources statement

try (

java.util.zip.ZipFile zf =

new java.util.zip.ZipFile(zipFileName);

java.io.BufferedWriter writer =

java.nio.file.Files.newBufferedWriter(outputFilePath, charset)

) {

// Enumerate each entry

for (java.util.Enumeration entries =

zf.entries(); entries.hasMoreElements();) {

// Get the entry name and write it to the output file

String newLine = System.getProperty("line.separator");

String zipEntryName =

((java.util.zip.ZipEntry)entries.nextElement()).getName() +

newLine;

writer.write(zipEntryName, 0, zipEntryName.length());

}

}

}

一个使用writer reader 操作properties文件的示例;注意同旧IO一样, 不要同时打开同一个文件的输入输出流(非全双工);

java.nio.charset.Charset charset =

java.nio.charset.StandardCharsets.UTF_8;

Paths.get("c:/new/conf.properties").getParent().toFile().mkdirs();

Paths.get("c:/new/conf.properties").toFile().createNewFile();

try(BufferedWriter w = Files.newBufferedWriter(Paths.get("c:/new/conf.properties"), charset)) {

Properties prop = new Properties();

prop.put("K1", "值1");

prop.put("K2", "V2");

prop.store(w, "hello");

} catch (Exception e) {

e.printStackTrace();

}

Properties prop = null;

try(BufferedReader r = Files.newBufferedReader(Paths.get("c:/new/conf.properties"));

) {

prop = new Properties();

prop.load(r);

System.out.println(prop);

} catch (Exception e) {

e.printStackTrace();

}

try(BufferedWriter w = Files.newBufferedWriter(Paths.get("c:/new/conf.properties"), charset)

) {

prop.put("K3", "值3");

prop.store(w, "hello");

} catch (Exception e) {

e.printStackTrace();

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值