最初是看OSChina,红薯发文看见的,比较好用。
操作的类只要是实现了AutoCloseable接口就可以在try语句块退出的时候自动调用close方法关闭流资源。
InputStream is = null;
OutputStream os = null;
try {
// 流
is = xxx;
os = xxx;
//use
is.read();
os.write();
} finally {
// close
if(stream != null){
try{
is.close();
}catch(Exeception e){
//xxx
}
try{
os.close();
}catch(Exeception e){
//xxx
}
}
}
改用新模式
try ( InputStream is = new FileInputStream("xx");
OutputStream os = new FileOutputStream("xx")
) {
//xxx
//不用关闭了,JVM帮你关闭流
}
常用于流对象,连接池等的自动关闭。
如果自己的类,实现AutoCloseable,实现其close方法,即可使用。
2. NIO2 文件处理Files
/**
* This class consists exclusively of static methods that operate on files,
* directories, or other types of files.
*
* In most cases, the methods defined here will delegate to the associated
* file system provider to perform the file operations.
*
* @since 1.7
*/
public final class Files {
读取方法
//读取字节
byte[] dataBytes = Files.readAllBytes(Paths.get("D:\\xxx"));
//readline
List lines = Files.readAllLines(Paths.get("D:\\xxx"));
写入方法
示例
//写入文件
Files.write(Paths.get("D:\\xxx"), "xxx".getBytes());
//指定模式写入,比如追加
Files.write(Paths.get("D:\\xxx"), "xxx".getBytes(), StandardOpenOption.APPEND);
/*****************************默认UTF-8编码,可以手工指定***********************************/
构造流模式
InputStream is = Files.newInputStream(path);
OutputStream os = Files.newOutputStream(path);
Reader reader = Files.newBufferedReader(path);
Writer writer = Files.newBufferedWriter(path);
//判断存在
Files.exists(path);
//
Files.createFile(path);
//
Files.createDirectory(path);
//文件列表,可以流运算遍历
Stream list(Path dir)
//文件列表
Stream walk(Path start, FileVisitOption... options)
Files.copy(in, path);
Files.move(path, path);
Files.delete(path);
//创建临时文件、临时目录:
Files.createTempFile(dir, prefix, suffix);
Files.createTempFile(prefix, suffix);
Files.createTempDirectory(dir, prefix);
Files.createTempDirectory(prefix);
Path对象
Path path = Paths.get("xxx", "name");
Path path = Paths.get("xxx/name");
Path path = Paths.get(URI.create("xxx路径"));
Path path = new File("xxx").toPath();
Path path = FileSystems.getDefault().getPath("xxx");
//Path、URI、File之间的转换
File file = new File("xxx");
Path path = file.toPath();
File file = p1.toFile();
URI uri = file.toURI();
3. 多异常统一处理
try {
//xxx
} catch (AException e) {
e.printStackTrace();
} catch (BException e) {
e.printStackTrace();
}
统一处理如下,粗化异常处理
try {
//xxx
} catch (AException | BException e) {
e.printStackTrace();
}
缺点是异常处理细粒度降低
4. switch(String)
switch可以支持字符串判断条件
switch (""){
case "":
break;
}
5. 泛型推导
List list = new ArrayList<>();