ms/packages/common/src/fs.ts

156 lines
3.5 KiB
TypeScript
Raw Normal View History

import '@ms/nashorn'
/*global Java, base, module, exports, require, __FILE__*/
const Path = Java.type("java.nio.file.Path");
const JavaString = Java.type("java.lang.String");
const File = Java.type("java.io.File");
const Files = Java.type("java.nio.file.Files");
const Collector = Java.type("java.util.stream.Collector")
const separatorChar = File.separatorChar;
const StandardCopyOption = Java.type("java.nio.file.StandardCopyOption");
/**
*
*/
export function concat(...args: string[]) {
return args.join(separatorChar);
}
/**
*
* @constructor(file)
* @constructor(dir,file)
* @returns {*}
*/
export function file(...opts: any[]): any {
if (!opts[0]) {
console.warn("文件名称不得为 undefined 或者 null !");
}
switch (opts.length) {
case 1:
var f = opts[0];
if (f instanceof File) {
return f;
}
if (typeof f === "string") {
return new File(f);
}
if (f instanceof Path) {
return f.toFile();
}
break;
default:
return new File(file(opts[0]), opts[1]);
}
}
/**
*
* @param path
*/
export function mkdirs(path: any) {
// noinspection JSUnresolvedVariable
file(path).parentFile.mkdirs();
}
/**
*
* @param file
*/
export function create(path: any) {
var f = file(path);
if (!f.exists()) {
mkdirs(f);
f.createNewFile();
}
}
/**
*
* @param file
* @returns {*}
*/
export function path(f: any) {
return file(f).canonicalPath;
}
/**
*
* @param inputStream
* @param target
* @param override
*/
export function copy(inputStream: any, target: any, override: any) {
Files.copy(inputStream, target.toPath(), StandardCopyOption[override ? 'REPLACE_EXISTING' : 'ATOMIC_MOVE']);
}
/**
*
* @param path
*/
export function read(path) {
var file = file(path);
if (!file.exists()) {
console.warn('读取文件', file, '错误 文件不存在!');
return;
}
// noinspection JSPrimitiveTypeWrapperUsage
return new JavaString(Files.readAllBytes(file.toPath()), "UTF-8");
}
/**
*
* @param path
* @param content
* @param override
*/
export function save(path, content, override) {
var file = file(path);
if (file.parentFile) {
file.parentFile.mkdirs();
}
Files.write(file.toPath(), new JavaString(content).getBytes("UTF-8"));
}
/**
*
* @param path
*/
export function list(path) {
var dir = file(path);
// noinspection JSValidateTypes
if (dir.isDirectory()) {
return Files.list(dir.toPath());
}
console.debug('路径', path, '不是一个目录 返回空数组!');
return [];
}
/**
*
* @param src
* @param des
* @param override
*/
export function move(src, des, override) {
Files.move(file(src).toPath(), file(des).toPath(),
override ? StandardCopyOption['REPLACE_EXISTING'] : StandardCopyOption['ATOMIC_MOVE'])
}
export function del(file) {
file = file(file);
if (!file.exists()) {
return;
}
if (file.isDirectory()) {
Files.list(file.toPath()).collect(Collector.toList()).forEach(function(f) {
del(f);
})
}
Files.delete(file.toPath());
}
export function exists(f) {
return file(f).exists()
}