Java读取文件,如果不存在的话创建它 [英] Java read a file, if it doesn't exist create it
本文介绍了Java读取文件,如果不存在的话创建它的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这里是我的代码
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));
//做些什么... //
}
br.close();
} catch(FileNotFoundException ex){
JOptionPane.showMessageDialog(null,Reading file error);
Logger.getLogger(LeggiDaFile.class.getName())。log(Level.SEVERE,null,ex);
$ b 我想知道如何检查fstream是否存在。如果它不存在,则必须创建一个新文件。我该怎么做?
谢谢
解决方案这是一个可能的解决方案:
public static void readData()throws IOException
{
File file = new File(path,filename); $!
$ b if(!file.isFile()&&!file.createNewFile())
{
抛出新的IOException(Error new file:+ file。 getAbsolutePath());
}
BufferedReader r = new BufferedReader(new FileReader(file));
try
{
//读取数据
} finally
{
r.close();
}
}
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
解决方案
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();
}
}
这篇关于Java读取文件,如果不存在的话创建它的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文