Java에서 파일을 다른 위치로 이동하려면 어떻게 해야 합니까?
파일을 어떤 위치에서 다른 위치로 이동하려면 어떻게 해야 합니까?프로그램을 실행하면 해당 위치에서 작성된 파일이 지정된 위치로 자동으로 이동합니다.어떤 파일이 이동되었는지 어떻게 알 수 있습니까?
myFile.renameTo(new File("/the/new/place/newName.file"));
파일 #이름 변경그러기 위해서(최소한 같은 파일 시스템상의 디렉토리간에 이름을 변경할 수 있을 뿐만 아니라, 디렉토리간에 이동할 수도 있습니다).
이 추상 경로 이름으로 표시된 파일의 이름을 바꿉니다.
이 방법의 동작의 많은 측면은 본질적으로 플랫폼에 의존합니다.파일 시스템 간에 파일을 이동하지 못할 수도 있고 원자성이 아닐 수도 있으며 대상 추상 경로 이름을 가진 파일이 이미 있는 경우 성공하지 못할 수도 있습니다.이름 변경 작업이 성공했는지 확인하려면 반환 값을 항상 확인해야 합니다.
보다 포괄적인 솔루션(예를 들어 디스크 간 파일 이동)이 필요한 경우 Apache Commons File Utils #move File을 참조하십시오.
Java 7 이상에서는 사용할 수 있습니다.Files.move(from, to, CopyOption... options)
.
예.
Files.move(Paths.get("/foo.txt"), Paths.get("bar.txt"), StandardCopyOption.REPLACE_EXISTING);
자세한 내용은 파일 설명서를 참조하십시오.
자바 6
public boolean moveFile(String sourcePath, String targetPath) {
File fileToMove = new File(sourcePath);
return fileToMove.renameTo(new File(targetPath));
}
Java 7(NIO 사용)
public boolean moveFile(String sourcePath, String targetPath) {
boolean fileMoved = true;
try {
Files.move(Paths.get(sourcePath), Paths.get(targetPath), StandardCopyOption.REPLACE_EXISTING);
} catch (Exception e) {
fileMoved = false;
e.printStackTrace();
}
return fileMoved;
}
File.renameTo
from Java IO를 사용하여 Java에서 파일을 이동할 수 있습니다.SO 질문도 참조해 주세요.
파일을 이동하려면 자카르타 공용 IO FileUtils.moveFile을 사용할 수도 있습니다.
에러에 대해서는,IOException
예외가 발생하지 않으면 파일이 이동되었음을 알 수 있습니다.
소스 및 대상 폴더 경로를 추가하십시오.
모든 파일과 폴더를 원본 폴더에서 대상 폴더로 이동합니다.
File destinationFolder = new File("");
File sourceFolder = new File("");
if (!destinationFolder.exists())
{
destinationFolder.mkdirs();
}
// Check weather source exists and it is folder.
if (sourceFolder.exists() && sourceFolder.isDirectory())
{
// Get list of the files and iterate over them
File[] listOfFiles = sourceFolder.listFiles();
if (listOfFiles != null)
{
for (File child : listOfFiles )
{
// Move files to destination folder
child.renameTo(new File(destinationFolder + "\\" + child.getName()));
}
// Add if you want to delete the source folder
sourceFolder.delete();
}
}
else
{
System.out.println(sourceFolder + " Folder does not exists");
}
Files.move(source, target, REPLACE_EXISTING);
를 사용할 수 있습니다.Files
물건
파일 상세보기
해당 태스크에 대해 외부 도구를 실행할 수 있습니다(예:copy
Windows 환경에서) 단, 코드를 이식 가능한 상태로 유지하기 위해 일반적인 접근법은 다음과 같습니다.
- 소스 파일을 메모리에 읽다
- 새 위치에 있는 파일에 내용을 쓰다
- 소스 파일 삭제
File#renameTo
소스와 타겟의 로케이션이 같은 볼륨에 있는 한, 동작합니다.개인적으로는 파일을 다른 폴더로 이동하는 데 사용하지 않을 것입니다.
이것을 시험해 보세요:-
boolean success = file.renameTo(new File(Destdir, file.getName()));
이 메서드는 내 프로젝트에 기존 논리가 있는 경우 치환 파일만으로 이 작업을 수행하기 위해 작성되었습니다.
// we use the older file i/o operations for this rather than the newer jdk7+ Files.move() operation
private boolean moveFileToDirectory(File sourceFile, String targetPath) {
File tDir = new File(targetPath);
if (tDir.exists()) {
String newFilePath = targetPath+File.separator+sourceFile.getName();
File movedFile = new File(newFilePath);
if (movedFile.exists())
movedFile.delete();
return sourceFile.renameTo(new File(newFilePath));
} else {
LOG.warn("unable to move file "+sourceFile.getName()+" to directory "+targetPath+" -> target directory does not exist");
return false;
}
}
이거 드셔보세요.
private boolean filemovetoanotherfolder(String sourcefolder, String destinationfolder, String filename) {
boolean ismove = false;
InputStream inStream = null;
OutputStream outStream = null;
try {
File afile = new File(sourcefolder + filename);
File bfile = new File(destinationfolder + filename);
inStream = new FileInputStream(afile);
outStream = new FileOutputStream(bfile);
byte[] buffer = new byte[1024 * 4];
int length;
// copy the file content in bytes
while ((length = inStream.read(buffer)) > 0) {
outStream.write(buffer, 0, length);
}
// delete the original file
afile.delete();
ismove = true;
System.out.println("File is copied successful!");
} catch (IOException e) {
e.printStackTrace();
}finally{
inStream.close();
outStream.close();
}
return ismove;
}
언급URL : https://stackoverflow.com/questions/4645242/how-do-i-move-a-file-from-one-location-to-another-in-java
'itsource' 카테고리의 다른 글
ASSERTION을 생성하려고 할 때 설명할 수 없는 mysql 오류가 발생했습니다. (0) | 2022.12.24 |
---|---|
수정된 환경에서 Python 하위 프로세스/팝업 (0) | 2022.12.24 |
2개의 인덱스의 "OR"을 더 빠른 솔루션으로 대체(UNION)? (0) | 2022.12.24 |
Log4J2 2.11.0 -> Log4J2 2.17.1 업그레이드 - Percona 5.7로의 mariaDB JDBC 드라이버에 대해 appender가 파손됨 - 잘못된 형식의 패킷 - maven - 해결됨 (0) | 2022.12.24 |
네이티브 XHR을 프로미스하려면 어떻게 해야 하나요? (0) | 2022.12.24 |