简体   繁体   中英

Is it possible to read a temporary file with an inputStream?

I am just interested to know whether it is possible to use an input Stream to search for a temporary file that is stored in the temp folder on a computer? I just need to test for something and need that temp file to be read. The idea is to basically create an XML file, store it as a temp file and read it via an input stream. The file is going to be quite big, so I need it to be a temp file so that I can delete it after I am done running my Junit test. The code can be found below. Any input is appreciated. Thanks.

Test class{
  private String name;
  private int age;

 //constructor
 //getter and setters
}

Another class {     
  private void createTemporaryXmlFile(){
    //create temp
    String temporaryDirectoryOp = System.getProperty("java.io.tmpdir");
    File tmpDirectory = new File(temporaryDirectoryOp );
    File fileStream = File.createTempFile("myFile",".xml", temporaryDirectoryOp );
    OutputStream outputStream= new FileOutputStream(fileStream );
  
    //marshall from Test POJO to XML
    JAXBContext jaxbContext = JAXBContext.newInstance(Test.class);
    Marshaller jaxbMarshaller = jaxbContext.createMarshaller();

    jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
    jaxbMarshaller.marshal(testClass, outputStream);

    fileStream.deleteOnExit();

    fos.close();
    dos.close();
  }
}

As Piotr said, temporary files and "normal" files are the same in regards of Java. You can just return fileStream from your function, do your testing and then call

fileStream.delete();

But with your call to fileStream.deleteOnExit(); (there's a typo in your code with the variable name), the file gets delete on the termination of the JVM (end of your test) anyway. But I think it's a better style to delete the file after usage and use "deleteOnExit" just as a fallback.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM