Java.io.File
renameTo method warning
renameTo
는 전적으로 플랫폼 의존적이다. 하나의 파일시스템에서 다른 파일시스템으로 복사가 안될수도 있다. 결론적으로 사용된 코드가 NFS나 다른 파일 시스템인 경우 또는 기타 플랫폼에 따라 될수도 있고 안될수도 있는 이상한 상황이 발생되지 않도록 파일을 복사하는 copy메소드를 만들어 사용하는것이 바람직하다.
InputStream to File function
public static final int DEFAULT_COPY_BUFFER_SIZE = 2048;
public static boolean copy(InputStream is, File outputFile) {
if (outputFile.exists() == false) {
try {
outputFile.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
FileOutputStream fos = null;
try {
fos = new FileOutputStream(outputFile);
} catch (FileNotFoundException e) {
e.printStackTrace();
fos = null;
}
if (fos != null) {
try {
int readByte = 0;
byte[] buffer = new byte[DEFAULT_COPY_BUFFER_SIZE];
while (true) {
readByte = is.read(buffer);
if (readByte > 0) {
fos.write(buffer, 0, readByte);
} else {
break;
}
}
} catch (IOException e) {
e.printStackTrace();
}
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
return true;
}
return false;
}
코드상에서 SDcard에 폴더 생성하기
가져온 URI에서 마지막 파일명을 가져오는 방법
String requestURI = request.getRequestURI();
page_id = requestURI.substring(requestURI.lastIndexOf("/")+1,requestURI.lastIndexOf("."));
파일을 삭제하는 방법
File.delete()
를 사용하면 된다.
File f = new File("test_9999.txt");
if (f.delete()) {
System.out.println("파일 또는 디렉토리를 성공적으로 지웠습니다: " + s);
} else {
System.err.println("파일 또는 디렉토리 지우기 실패: " + s);
}
파일 이동 방법
File.renameTo()
를 사용하면 된다. 단, 옮길 위치에 파일이 존재할 경우 실패된다.
Delete a non-empty directory in JAVA
비어있지 않은 디렉터리 삭제하는 방법은 아래와 같다.
// 비어있지 않은 디렉터리를 삭제한다.
public static void deleteDirectory(String path) {
if (path != null && path.length() > 0) {
File f = new File(path);
if (f.exists() == true) {
File[] files = f.listFiles();
for (File file : files) {
if (file.isDirectory()) {
deleteDirectory(f.getPath());
} else {
file.delete();
}
}
}
f.delete();
}
}