如果文件不存在,如何使outputstream生成文件?
我在创建outputstream文件时遇到问题.
I have a problem with creating an outputstream file.
OutputStream output = new FileOutputStream(username + ".txt");
byte buffer[] = data.getBytes();
output.write(buffer);
output.close();
工作正常,直到我做出另一种方法:
It worked fine, until I made another method:
public void actionPerformed (ActionEvent e) //When a button is clicked
{
if (e.getSource() == encrBtn)
{
menu.setVisible(false);
createProfile();
menu.setVisible(true);
}
else
{
if (e.getSource() == decrBtn)
{
menu.setVisible(false);
viewProfile();
menu.setVisible(true);
}
else
{
if (e.getSource() == exitBtn)
{
JOptionPane.showMessageDialog(null, "Goodbye!");
System.exit(0);
}
}
}
}
以前,我在调用
createprofile();
方法(输出流所在的方法).但是现在我得到了
method (in which the output stream is). But now I get
ProfileEncryption_2.java:54: error: actionPerformed(ActionEvent) in ProfileEncryption_2 cannot implement actionPerformed(ActionEvent) in ActionListener
public void actionPerformed (ActionEvent e) throws Exception //When a button is clicked
^
overridden method does not throw Exception
以前,我想知道是否还有另一种引发异常的方法:无法实现actionPerformed( ActionListener) 但是现在我认为最好以某种方式强制输出流制作文件.我用谷歌搜索了多个短语,但是现在我知道该怎么做了……我发现的东西也不起作用.
Previously, I was wondering if there was another way to throw the exception: cannot implement actionPerformed(ActionEvent) in ActionListener But now I think that it would be better to somehow force the outputstream to make the file. I have googled multiple phrasings of this, but I do now know how to do this... the things I found did not work either.
ActionListener
接口没有声明它是actionPerformed
方法,因为它抛出了任何类型的Exception
,您不能更改此签名.
The ActionListener
interface does not declare it's actionPerformed
method as throwing any type of Exception
, you can not change this signature.
您需要从方法中捕获并管理异常.
You need to catch and manage the exception from within the method.
public void actionPerformed(ActionEvent e) //When a button is clicked
{
if (e.getSource() == encrBtn) {
menu.setVisible(false);
try {
createProfile();
} catch (Exception exp) {
exp.printStackTrace();
JOptionPane.showMessageDialog(this, "Failed to create profile", "Error", JOptionPane.ERROR_MESSAGE);
}
menu.setVisible(true);
} else {
//...
}
}
FileOutputStream
能够创建文件(如果文件不存在),但是如果路径不存在或者您没有足够的权限来写入指定位置,则可能会出现问题,或者还有许多其他可能的问题...
FileOutputStream
is capable of creating the file if it does not exist, but may have issues if the path doesn't or if you don't have adequate permissions to write to the specified location or any number of other possible issues...