Home | 简体中文 | 繁体中文 | 杂文 | Github | 知乎专栏 | Facebook | Linkedin | Youtube | 打赏(Donations) | About
知乎专栏

15.2. 临时文件

		
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;
    }