코드 사본은 다음과 같습니다.
패키지 com.xyq.io.simply.core;
import java.io.file;
import java.io.ioexception;
java.nio.file.filevisitresult import;
import java.nio.file.filevisitor;
import java.nio.file.files;
java.nio.file.path 가져 오기;
java.nio.file.paths import;
java.nio.file.standardCopyoption 가져 오기;
import java.nio.file.attribute.basicfileattributes;
java.util.arraylist 가져 오기;
Java.util.list 가져 오기;
import com.xyq.io.enums.filetypemode;
import com.xyq.io.enums.optionfile_type;
import com.xyq.io.inf.newnioinf;
import com.xyq.io.util.findfileutil;
import com.xyq.io.util.md5util;
공개 클래스 Newnio는 NewNioInf {
/***
* 파일을 복사하거나 이동하십시오
*/
@보수
public boolean copeormovefile (String Src, String Tar, OptionFile_Type 유형) {
reallcopeormovefile (paths.get (src), tar, type)를 반환합니다.
}
개인 부울 RealCopeorMoveFile (Path SrcPath, String Tar,
옵션 파일 _type 유형) {
경로 tarpath = null;
부울 copesuccess = true;
// 원본 파일이 있어야합니다
if (srcpath.tofile (). Exists ()) {
/***
* 원래 경로가 삭감되면 폴더로 간주됩니다.
*/
if (isdir (tar))
tarpath = paths.get (tar + file.separator
+ srcpath.tofile (). getName ());
또 다른
tarpath = paths.get (tar);
/***
* 그런 다음 n 번 (매개 변수로 사용할 수 있음) 복사 작업 (오류 후 재 연결), 복사, 사본 속성, 복사 작업을 롤백 옵션을 사용할 수 없습니다.
*/
for (int i = 0; i <3; i ++) {
/***
* 대상 파일이 이미 존재하는 경우
*/
if (tarpath.tofile (). Exists ()) {
/***
* 두 폴더가 동일인지 확인하면 복사 옵션에서 복사 할 필요가 없습니다.
*/
// 복사
if (OptionFile_type.cope.equals (type)) {
if (equalsfile (srcpath.tofile (), tarpath.tofile ()))
진실을 반환하십시오.
또 다른
copesuccess = copefile (srcpath, tarpath, true);
}
/***
* 작동, 정상적인 상황에서 두 파일이 동일하다면 매우 조심하십시오.
* 그런 다음 원본 파일을 삭제하십시오. 그러나 두 파일이 동일하고 주소도
* 동일하다면 원래 파일은 동일하고 삭제할 수 없기 때문에 원본을 삭제할 수 없습니다.
*/
else if (옵션 파일 _type.move.equals (type)) {
if (equalsfile (srcpath.tofile (), tarpath.tofile ())) {
if (! srcpath.tofile (). getAbsolutefile ())
.equals (tarpath.tofile (). getAbsolutefile ()))
노력하다 {
files.delete (srcpath);
/***
* 수동으로 진짜를 가리키는 이유는 이전 삭제에 실패가 발생할 수 있기 때문입니다.
*/
if (! copesuccess)
copesuccess = true;
} catch (ioexception e) {
copesuccess = false;
}
// 정면에 예외가 있기 때문에 직접 돌아 오지 않습니다.
또 다른
진실을 반환하십시오.
} 또 다른
copesuccess = movefile (srcpath, tarpath);
}
}
/***
* 대상 파일이 존재하지 않으면 먼저 상위 클래스 폴더를 생성 할 수 있는지 (부모 클래스 폴더가 존재하는지 또는 생성 할 수 있음)를 만들 수 있는지 확인한 다음 생성 할 수 있습니다.
*/
또 다른 {
파일 par = tarpath.getParent (). tofile ();
/***
* 부모 클래스 폴더가 존재하지 않고 생성 할 수없는 경우 복사 할 필요가 없습니다.
*/
if (! par.exists () &&! par.mkdirs ())
copesuccess = false;
else if (옵션 파일 _type.cope.equals (type))
copesuccess = copefile (srcpath, tarpath, false);
else if (옵션 파일 _type.move.equals (type))
copesuccess = movefile (srcpath, tarpath);
}
// 조작이 성공하면 루프가 뛰어납니다.
if (copesuccess)
부서지다;
}
} 또 다른
copesuccess = false;
반환 대처자;
}
/***
* 파일을 복사하십시오
*/
Private Boolean Copefile (Path SrcPath, Path Tarpath, Boolean isexist) {
if (isexist)
노력하다 {
files.copy (srcpath, tarpath,
StandardCopyOption.replace_existing,
StandardCopyOption.copy_attributes);
} catch (ioexception e) {
거짓을 반환합니다.
}
또 다른
노력하다 {
files.copy (srcpath, tarpath, StandardCopyoption.copy_attributes);
} catch (ioexception e) {
거짓을 반환합니다.
}
진실을 반환하십시오.
}
/***
* 파일 이동, 속성 옵션을 사용할 수 없습니다
*
* @param srcpath
* @param tarpath
* @반품
*/
개인 부울 MoveFile (Path SrcPath, Path TarPath) {
노력하다 {
files.move (srcpath, tarpath, StandardCopyoption.atomic_move);
} catch (ioexception e) {
거짓을 반환합니다.
}
진실을 반환하십시오.
}
/***
* 경로 경로가 폴더인지 확인하십시오
*
* @param 경로
* @반품
*/
개인 부울 isdir (문자열 경로) {
char lastc = path.charat (path.length () -1);
if (lastc == '//'|| lastc == '/')
진실을 반환하십시오.
거짓을 반환합니다.
}
/***
* 이것은 두 파일이 동일한 지 여부를 확인하기위한 것입니다. 단순한 검증 일 뿐이며 확인을 위해 MD5를 사용해야합니다.
*/
public boolean equalsfile (파일 SRC, 파일 타르) {
// 두 파일의 길이가 다르면 두 파일은 분명히 다릅니다.
if (src.length ()! = tar.length ())
거짓을 반환합니다.
if (! src.getName (). Equals (tar.getName ())
||. srclastmodified ()!
md5util.encoderfilebymd5 (src) .equals를 반환합니다.
md5util.encoderfilebymd5 (tar));
진실을 반환하십시오.
}
/***
* 폴더를 복사하거나 이동하십시오
*/
@보수
공개 void copeormovedirectory (String SRC, Final String Tar, int Tiersize,
최종 옵션 file_type 유형) {
if (! 새 파일 (src) .exists ())
새로운 runtimeexception을 던지십시오 ( "원래 폴더는 찾을 수 없음" + SRC);
최종 int ultpos = getRootPosition (새 파일 (SRC), Tiersize);
if (hitpos! = -1) {
노력하다 {
files.walkfiletree (paths.get (src), 새 filevisitor <path> () {
문자열 tardirstring = null;
/***
* 폴더에 도착하기 전에 먼저 대상 경로를 작성하십시오.
*
* @param dir
* @param attrs
* @반품
* @throws ioexception
*/
@보수
public filevisitresult previsitDirectory (Path Dir,
BasicFileAtTributes attrs) IoException {
tardirstring = dir.tofile (). getabsolutepath ();
tardirstring = tar + tardirstring.substring (withpos)
+ file.separator;
반환 FilevisItresult.continue;
}
/***
* 파일에 도착한 후 복사하거나 이동
*
* @param 파일
* @param attrs
* @반품
* @throws ioexception
*/
@보수
public filevisitresult visitfile (경로 파일,
BasicFileAtTributes attrs) IoException {
파일 f = file.tofile ();
if (f.exists () && f.canread () &&! f.ishidden ())
realcopeormovefile (파일, tardirstring, type);
반환 FilevisItresult.continue;
}
@보수
public filevisitresult visitfilefailed (경로 파일,
IoException exc) IoException {
반환 FilevisItresult.continue;
}
/***
* 폴더에 도착한 후
*
* @param dir
* @param excc
* @반품
* @throws ioexception
*/
@보수
public filevisitresult postvisitDirectory (path dir,
IoException exc) IoException {
반환 FilevisItresult.continue;
}
});
} catch (예외 e) {
e.printstacktrace ();
}
// 컷 작업이고 컷이 성공하면 모든 폴더를 삭제해야합니다.
if (OptionFile_type.move.equals (type) && isblockdir (src))
Deldir (SRC);
} 또 다른
새로운 runtimeexception을 던지십시오 ( "부모 클래스 폴더 계층 오류 ~~~");
}
/***
* 지정된 레벨에 따라 지정된 드라이브 문자의 위치를 가져옵니다.
*/
private int getRootPosition (파일 파일, Int Tier) {
if (file! = null) {
문자열 path = file.getabsolutepath ();
int cc = 0;
for (int i = path.length () -1; i> = 0; i-) {
if (path.charat (i) == '//') {
CC ++;
if (cc == Tier + 1) {
CC = I;
반환 CC;
}
}
}
}
반품 -1;
}
/***
*이 폴더에 파일이 있는지 확인하십시오.
*
* @param dirpath
* @반품
*/
개인 부울 isblockdir (String dirpath) {
파일 dir = 새 파일 (dirpath);
file [] dirlist = dir.listfiles ();
if (dirlist == null || dirlist.length == 0)
진실을 반환하십시오.
또 다른 {
// 파일을 찾습니다
for (파일 F : Dirlist)
if (! f.isdirectory ())
거짓을 반환합니다.
}
진실을 반환하십시오.
}
/***
* 빈 폴더를 삭제합니다
*
* @param dirpath
*/
개인 void deldir (String dirpath) {
파일 dir = 새 파일 (dirpath);
file [] dirlist = dir.listfiles ();
if (dirlist == null || dirlist.length == 0)
dir.delete ();
또 다른 {
// 모든 파일을 삭제합니다
for (파일 F : Dirlist)
if (f.isdirectory ())
deldir (f.getabsolutepath ());
또 다른
f.delete ();
// 현재 폴더에서 모든 파일을 삭제 한 후 폴더 삭제
Dirlist = dir.listfiles ();
if (dirlist.length == 0)
dir.delete ();
}
}
/***
* 파일 유형에 따라 관련 파일을 찾으십시오
*/
@보수
공개 목록 <string> findfilesbytype (String dir, String [] 키,
부울 ismatchcase) IoException {
List <string> list = new ArrayList <string> ();
files.walkfiletree (Paths.get (dir), 새로운 findfileutil (키, ismatchcase,
list, filetypemode.types);
반환 목록;
}
/***
* 파일 이름에 따라 관련 파일을 찾으십시오
*/
@보수
공개 목록 <string> findfilesbyName (String dir, String [] 키,
부울 ismatchcase) IoException {
List <string> list = new ArrayList <string> ();
files.walkfiletree (Paths.get (dir), 새로운 findfileutil (키, ismatchcase,
list, filetypemode.names));
반환 목록;
}
public static void main (String [] args)은 ioexception {
newnioinf inf = new newnio ();
inf.copeormovefile ( "e : /cc/dd/11.txt", "e :/xx/xxx/zzz/",
옵션 파일 _type.cope);
inf.copeormovedirectory ( "e : // bb // cc // dd", "e : //", 1, 옵션 file_type.move);
system.out.println (inf.findfilesbyname ( "d : // stlokspace", new String [] { "txt"},
false) .size ());
}
}
----------------------------------
패키지 com.xyq.io.enums;
/***
* 파일 유형
* @Author XYQ
*
*/
공개 열거 형 FiletypeMode {
유형, 이름
}
--------------------------------------------
패키지 com.xyq.io.enums;
/***
* 작동 파일 유형
* @Author XYQ
*
*/
public enum optionfile_type {
COPE, 이동;
}
--------------------------------------------------------- --------------------------------------------------------- ----------------------------
패키지 com.xyq.io.inf;
import java.io.ioexception;
Java.util.list 가져 오기;
import com.xyq.io.enums.optionfile_type;
공개 인터페이스 newnioinf {
/***
* 파일을 복사하거나 이동하십시오
* @param src
* @param tar
* @반품
*/
public boolean copeormovefile (String SRC, String Tar, OptionFile_Type 유형);
/***
* 폴더를 복사하거나 이동하십시오
* @param src
* @param tar
* @Param Tiersize 계층 구조, 복사 후 0은 현재 폴더 일뿐입니다. +1은 첫 번째 수준의 상위 클래스 폴더를 추가하는 것을 의미하지만 (부모 클래스 컨텐츠를 복사하지 않음)
* @param 유형
*/
public void copeormovedirectory (String SRC, String Tar, int Tiersize, OptionFile_Type 유형);
/**
* 파일 유형을 기반으로 관련 파일 수집을 찾아 여러 유형의 경우 쉼표로 분리합니다.
*
* @param dir
* 목차
* @param 키
* 파일 유형
* @param ismatchcase
* 사례에 민감한 지 여부
* @반품
* @throws ioexception
*/
list <string> findfilesbytype (문자열 dir, string [] 키, 부울 ismatchcase)
ioexception을 던집니다.
/**
* 파일 이름을 기반으로 관련 파일 수집을 찾으십시오.
*
* @param dir
* 목차
* @param 키
* 파일 이름
* @param ismatchcase
* 사례에 민감한 지 여부
* @반품
* @throws ioexception
*/
list <string> findfilesbyName (String dir, String [] 키, 부울 ismatchcase)
ioexception을 던집니다.
}
--------------------
패키지 com.xyq.io.util;
import java.io.file;
import java.io.ioexception;
java.nio.file.filevisitresult import;
java.nio.file.path 가져 오기;
import java.nio.file.simplefilevisitor;
import java.nio.file.attribute.basicfileattributes;
Java.util.list 가져 오기;
import com.xyq.io.enums.filetypemode;
공개 클래스 FindFileUtil 확장 SimpleFilevisitor <Path> {
/***
* 키워드 목록, 케이스 변환 여부, 반환 결과 세트
*/
개인 문자열 [] keyArray = null;
개인 부울 ismatchcase;
개인 목록 <String> resultList;
개인 파일 형 모드 모드;
Public FindFileutil (String [] KeyArray, 부울 ISMatchCase,
List <string> resultList, FileTypEmode 모드) {
this.keyArray = keyArray;
this.ismatchcase = ismatchcase;
this.resultlist = resultList;
this.mode = 모드;
}
@suppresswarnings ( "미사용")
개인 findfileutil () {
}
@보수
public filevisitresult visitfile (경로 파일, BasicFileAttributes attrs)
IoException {{
파일 f = file.tofile ();
if (f.exists () && f.canread () &&! f.ishidden ())
if (this.keyArray! = null) {
for (문자열 키 : this.keyArray) {
if (! this.iscatchcase)
key = key.tolowercase ();
if (matchfile (파일, this.mode, key, ismatchcase)))
resultList.add (file.toString ());
}
}
반환 FilevisItresult.continue;
}
/***
* 케이스 및 유형 또는 이름을 기준으로 파일 일치
*
* @param 파일
* @param 모드
* @param 키
* @param ismatchcase
* @반품
*/
개인 부울 matchfile (경로 파일, filetypeMode 모드, 문자열 키,
부울 ismatchcase) {
파일 f = file.tofile ();
if (f.exists () && f.canread () &&! f.ishidden ()
&&! "시스템 볼륨 정보".Equals (f.getName ())) {
문자열 filename = null;
if (filetypeMode.types.equals (mode)) {
filename = file.tostring ();
ismatchcase? filename.endswith (key) : filename을 반환합니다
.TOLOWERCASE (). ENDSWITH (키);
} else if (filetypemode.names.equals (mode)) {
filename = file.tofile (). getName ();
ismatchcase를 반환 하시겠습니까? (filename.indexof (key) == -1? false
: 진실)
: (filename.tolowercase (). indexof (key) == -1? false
: 진실);
}
}
거짓을 반환합니다.
}
@보수
public filevisitresult visitfilefailed (Path File, ioException excc)
IoException {{
// 오류 메시지에 x :/시스템 볼륨 정보가 포함 된 경우 시스템의 숨겨진 디스크를 의미하며 읽을 수 없습니다.
System.out.println (exc.getMessage ());
반환 FilevisItresult.continue;
}
}
----------------------------------
패키지 com.xyq.io.util;
import java.io.closable;
공개 클래스 CloseIoutil {
/***
* IO 스트림을 닫습니다
*
* @Param CLS
*/
public static void closeall (Closable ... Cls) {
if (cls! = null) {
for (closeable cl : cls) {
노력하다 {
if (cl! = null)
cl.close ();
} catch (예외 e) {
} 마지막으로 {
cl = null;
}
}
}
}
}
--------------------------------------------------------- --------------------------------------------------------- ----------------------------
패키지 com.xyq.io.util;
import java.io.bufferedInputStream;
import java.io.file;
import java.io.fileInputStream;
import java.io.ioexception;
java.io.unsupportedencodingException 가져 오기;
java.security.messagegegest;
java.security.nosuchalgorithmexception import;
import sun.misc.base64encoder;
공개 클래스 md5util {
/***
* 암호화 된 문자열
*
* @param str
* @반품
* @throws nosuchalgorithmexception
* @throws UnsupportedEncodingException
*/
public static string encoderstringbymd5 (String str)
Nosuchalgorithmexception, UnsupportedencodingException {
// 계산 방법을 결정합니다
MessageDigest MD5 = MessageDigest.getInstance ( "MD5");
Base64encoder base64en = 새로운 Base64encoder ();
// 암호화 된 문자열
문자열 newsr = base64en.encode (md5.Digest (str.getBytes ( "UTF-8")));
리턴 Newsr;
}
/***
* 암호화 된 파일
*
* @param 파일
* @반품
* @throws nosuchalgorithmexception
* @throws ioexception
*/
public static string encoderfilebymd5 (파일 파일) {
문자열 newsstr = null;
fileInputStream fis = null;
bufferedInputStream bis = null;
노력하다 {
// 계산 방법을 결정합니다
MessageDigest MD5 = MessageDigest.getInstance ( "MD5");
Base64encoder base64en = 새로운 Base64encoder ();
바이트 [] 버퍼 = 새로운 바이트 [1024];
fis = new FileInputStream (파일);
BIS = 새로운 BufferedInputStream (FIS);
int 길이 = -1;
while ((길이 = bis.read (버퍼))! = -1)
md5.update (버퍼, 0, 길이);
// 암호화 된 문자열
Newsstr = base64en.encode (md5.digest ());
} catch (예외 e) {
e.printstacktrace ();
} 마지막으로 {
closeioutil.closeall (bis, fis);
}
리턴 Newsr;
}
public static void main (String [] args)은 Nosuchalgorithmexception, UnsupportedencodingException {
System.out.println (encoderstringbymd5 ( "23"));
}
}