Java read a file, if it doesn't exist create it
Solution 1
Here's a possible solution:
public static void readData() throws IOException
{
File file = new File(path, filename);
if (!file.isFile() && !file.createNewFile())
{
throw new IOException("Error creating new file: " + file.getAbsolutePath());
}
BufferedReader r = new BufferedReader(new FileReader(file));
try
{
// read data
}finally
{
r.close();
}
}
Solution 2
Something's missing in your code - there's a closing brace with no corresponding opening brace.
But to answer your question, create a File
object first and use exists()
, then createNewFile()
if exists()
returns false
. Pass the File
object instead of the filename to the FileInputStream
constructor.
BTW, it would have taken you less time to google the answer than it did to type in your question here.
Solution 3
To check if the file filename
exists in path
, you can use new File(path, filename).exists()
.
The exists method returns true if a file or directory exists on the filesystem for the specified File
.
To verify that the file is a file and not a directory, you can use the isFile method.
See the javadoc for java.io.File for more information.
Fseee
Updated on June 04, 2022Comments
-
Fseee almost 2 years
here's my code
public String path; public String fileName; public static void readData() throws IOException{ try { path="myPath" fileName="myFileName"; fstream = new FileInputStream(path+fileName); br = new BufferedReader(new InputStreamReader(fstream)); //do something...// } br.close(); } catch (FileNotFoundException ex) { JOptionPane.showMessageDialog(null, "Reading file error"); Logger.getLogger(LeggiDaFile.class.getName()).log(Level.SEVERE, null, ex); } }
I wanted to know how to check if the fstream exists. If it doesn't exist, a new file has to be created. How can I do this? Thanks