Java读取一个文件,如果它没有';我不能创造它
这是我的密码Java读取一个文件,如果它没有';我不能创造它,java,file,text,Java,File,Text,这是我的密码 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(
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);
}
}
我想知道如何检查fstream是否存在。如果不存在,则必须创建一个新文件。我该怎么做?
感谢要检查文件
文件名是否存在于路径中,您可以使用新文件(路径,文件名).exists()
如果指定的文件的文件系统上存在文件或目录,则返回true
要验证文件是文件而不是目录,可以使用
有关详细信息,请参阅。您已经捕获了FileNotFoundException
,在这里您知道您要读取的文件不存在,可以创建它
if(new File("filename").exists())
...
它应该可以满足您的需要。这里有一个可能的解决方案:
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();
}
}
代码中缺少了一些内容-有一个右大括号,但没有相应的右大括号
但要回答您的问题,请先创建一个文件
对象并使用exists()
,然后使用createNewFile()
如果exists()
返回false
。将文件
对象而不是文件名传递给文件输入流
构造函数
顺便说一句,用谷歌搜索答案所花的时间比在这里输入问题所花的时间要少。或者更好的新文件(路径,文件名).exists()
,它将自动为您所使用的操作系统插入正确的路径分隔符。您可能还想看看如何使用InputStreamReader
,指定字符集
,而不是使用默认字符集的文件读取器
。。。