Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create a File object in memory from a string in Java

Tags:

java

file

file-io

I have a function that accepts File as an argument. I don't want to create/write a new File (I don't have write access to filesystem) in order to pass my string data to the function. I should add that the String data don't exist in a file (so I cannot read my data from a file).

Can I use Streams and "cast" them to File objects?

like image 633
Jon Romero Avatar asked Aug 16 '11 19:08

Jon Romero


People also ask

Why do we create file object in Java?

Java File class represents the files and directory pathnames in an abstract manner. This class is used for creation of files and directories, file searching, file deletion, etc. The File object represents the actual file/directory on the disk. Following is the list of constructors to create a File object.

How do you create a file and directory in Java?

File provides methods like createNewFile() and mkdir() to create new file and directory in Java. These methods returns boolean, which is the result of that operation i.e. createNewFile() returns true if it successfully created file and mkdir() returns true if the directory is created successfully.


1 Answers

Usually when a method accepts a file, there's another method nearby that accepts a stream. If this isn't the case, the API is badly coded. Otherwise, you can use temporary files, where permission is usually granted in many cases. If it's applet, you can request write permission.

An example:

try {
    // Create temp file.
    File temp = File.createTempFile("pattern", ".suffix");

    // Delete temp file when program exits.
    temp.deleteOnExit();

    // Write to temp file
    BufferedWriter out = new BufferedWriter(new FileWriter(temp));
    out.write("aString");
    out.close();
} catch (IOException e) {
}
like image 133
Chris Dennett Avatar answered Sep 20 '22 10:09

Chris Dennett