create a temporary file with a specified name in java

泄露秘密 提交于 2019-12-23 04:26:31

问题


I have a Byte[] array that i want to put it's content into a temporary file .

I have tryied to do it like this

try {
            tempFile = File.createTempFile("tmp", null);
            FileOutputStream fos = new FileOutputStream(tempFile);
            fos.write(sCourrier.getBody());
        } catch (IOException e) {
            e.printStackTrace();
        }

but i want that I specify the filename by myself so not generated by the jvm


回答1:


You can directly give the location and file name or You can access local filesystem and find the temp directory

 String tempDir=System.getProperty("java.io.tmpdir");

you can use temp directory and your custom file name.

public static void main(String[] args) {
    try {
        String tempDir=System.getProperty("java.io.tmpdir");
        String sCourrier ="sahu";
        File file = new File(tempDir+"newfile.txt");
        FileOutputStream fos = new FileOutputStream(file);
        fos.write(sCourrier.getBytes());
    } catch (IOException e) {
        e.printStackTrace();
    }


来源:https://stackoverflow.com/questions/44410264/create-a-temporary-file-with-a-specified-name-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!