Java.io.File
lastmod 2018-08-17created 2014-05-265 edits
renameTo method warning
renameTo is entirely platform-dependent. Copying from one file system to another may not work. In conclusion, to avoid odd situations where the code may or may not work depending on NFS, another file system, or the platform, it is better to write and use your own copy method that copies the file.
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;
}
Creating a folder on the SD card in code
Getting the last file name from a URI
String requestURI = request.getRequestURI();
page_id = requestURI.substring(requestURI.lastIndexOf("/")+1,requestURI.lastIndexOf("."));
Deleting a file
Use File.delete().
File f = new File("test_9999.txt");
if (f.delete()) {
System.out.println("파일 또는 디렉토리를 성공적으로 지웠습니다: " + s);
} else {
System.err.println("파일 또는 디렉토리 지우기 실패: " + s);
}
Moving a file
Use File.renameTo(). However, it fails if a file already exists at the destination.
Delete a non-empty directory in JAVA
A non-empty directory can be deleted as follows.
// 비어있지 않은 디렉터리를 삭제한다.
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();
}
}