![](/img/trans.png)
[英]Save a http link in word document with java BufferedWriter
[英]Java BufferedWriter Save As operation
我正在尝试在Java中模拟另存为功能。 我想为其选择一个文件名,就像之前将其保存到的代码一样
myData.dat
这在我的Main.Class的菜单中使用,它将查找
else if (option.compareTo("8") == 0){
manualLib.save();}
public void save(){
String content = "";
for (int i = 0; i < library.size(); i++){
for (int bar = 0; bar < library.get(i).size(); bar++){
content += library.get(i).get(bar).getSerial() + "\n";
content += library.get(i).get(bar).getTitle() + "\n";
content += library.get(i).get(bar).getAuthor() + "\n";
content += library.get(i).get(bar).onLoan() + "\n";
content += library.get(i).get(bar).getBorrower() + "\n";
}
}
Writer output;
try {
output = new BufferedWriter(new FileWriter("myData.dat"));
try {
output.write(content);
}
finally {
output.close();
System.out.println("Successfully saved to myData.dat file.");
}
} catch (IOException e) {
e.printStackTrace();
}
}
什么是实现这一目标的好方法?
您可以使用JFileChooser 。 这将为您提供一个“简单”的用户界面,让用户选择文件(或文件名)。 然后,将您的myData.dat
替换为chooser.getSelectedFile().getName()
返回的值。
我还没有编译它,但是您的代码最终应该看起来像:
public void save(){
String content = "";
for (int i = 0; i < library.size(); i++){
for (int bar = 0; bar < library.get(i).size(); bar++){
content += library.get(i).get(bar).getSerial() + "\n";
content += library.get(i).get(bar).getTitle() + "\n";
content += library.get(i).get(bar).getAuthor() + "\n";
content += library.get(i).get(bar).onLoan() + "\n";
content += library.get(i).get(bar).getBorrower() + "\n";
}
}
Writer output;
JFileChooser chooser = new JFileChooser();
DatFilter filter = new DatFilter();
filter.addExtension("dat");
filter.setDescription(".dat files");
chooser.setFileFilter(filter);
int returnVal = chooser.showOpenDialog(null);
String fileName = new String();
if(returnVal == JFileChooser.APPROVE_OPTION) {
fileName=chooser.getSelectedFile().getName();
}
try {
output = new BufferedWriter(new FileWriter(fileName));
try {
output.write(content);
}
finally {
output.close();
System.out.println("Successfully saved to "+fileName+" file.");
}
} catch (IOException e) {
e.printStackTrace();
}
}
然后上课
public class DatFilter extends FileFilter {
//should accept only dirs and .dat files
public boolean accept(File f) {
if (f.isDirectory()) {
return true;
}
String extension = null;
String s = f.getName();
int i = s.lastIndexOf('.');
if (i > 0 && i < s.length() - 1) {
extension = s.substring(i+1).toLowerCase();
}
if (extension != null) {
if (extension.equals("dat"){
return true;
} else {
return false;
}
}
return false;
}
//The description of this filter
public String getDescription() {
return ".dat Files";
}
}
save
方法中添加参数以获取此路径,并使用它代替myData.dat
save
,它使用Main.class中存储的路径调用save
参数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.