知乎专栏 |
目录
File file = new File("HelloWorld.jpeg"); String fileName = file.getName(); String suffix = fileName.substring(fileName.lastIndexOf(".") + 1); System.out.println(suffix);
File configFile = new File(System.getProperty("user.dir") + configPath); System.out.printf("configFile : %s\n", configFile.getAbsolutePath());
//判断cache目录是否存在的代码,如果不存在则创建cache目录 String path="/tmp/cache"; File dirname = new File(path); //目录不存在 if (!dirname.isDirectory()) { dirname.mkdir(); //创建目录 }
public static boolean delete(String pathname) { boolean status = false; File file = new File(pathname); if (file.isFile() && file.exists()) { status = file.delete(); } return status; }
public static void deleteOnExit(String pathname) { File file = new File(pathname); file.deleteOnExit(); }
package cn.netkiller.file; import java.io.File; import java.io.IOException; public class CreateTempFileExample { public static void main(String[] args) { try{ //create a temp file File temp = File.createTempFile("temp-file-name", ".tmp"); System.out.println("Temp file : " + temp.getAbsolutePath()); }catch(IOException e){ e.printStackTrace(); } } }
Temp file : C:\Users\neo\AppData\Local\Temp\temp-file-name623426.tmp
指定目录创建临时文件,运行之后将会在 /tmp/convert 目录中创建文件
@SneakyThrows public InputStream convertInputStreamAmrToPcm(InputStream inputStreamAmr) { // UUID uuid = UUID.randomUUID(); // String filename = uuid.toString(); String filename = "convert-"; File source = File.createTempFile(filename, ".amr", new File("/tmp/convert")); File target = File.createTempFile(filename, ".pcm", new File("/tmp/convert")); if (!target.getParentFile().isDirectory()) { boolean directory = target.getParentFile().mkdirs(); } log.info("Source: {}, Target: {}", source.getAbsolutePath(), target.getAbsolutePath()); source.deleteOnExit(); target.deleteOnExit(); inputStreamAmr.transferTo(new FileOutputStream(source)); boolean status = audioFormatConversion(source, target); log.info("Amr To Pcm: {}", status); if (!status) { return null; } InputStream inputStream = new FileInputStream(target); return inputStream; }