我正在写一个文件,我希望根据用户输入获得文件名,但是将其保存在与.java文件所在的目录不同的目录中。有没有代码可以做到这一点?我正在使用Java。这是我的代码:
import java.io.*;
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
public class Login extends Frame implements ActionListener
{ Label l1=new Label("user name");
Label l2=new Label("password");
Label l3=new Label(" ");
TextField t1=new TextField();
TextField t2=new TextField();
Button b= new Button("Sign up");
Button b1= new Button("Login");
public Login()
{ add(l1);
add(t1);
add(l2);
add(t2);
add(b1);
add(b);
add(l3);
l1.setBounds(20,45,70,20);
t1.setBounds(180,45,200,20);
l2.setBounds(20,95,70,20);
t2.setBounds(180,95,200,20);
b1.setBounds(310,145,70,20);
b1.addActionListener(this);
b.setBounds(310,195,70,20);
b.addActionListener(this);
t2.setEchoChar('*');
addWindowListener(new mwa());
}
public void actionPerformed(ActionEvent e){
if(b == e.getSource() ){
l3.setText("Welc "+t1.getText());
// The name of the file to open.
String fileName = "C:/Users/Brandon/Desktop/Java/Accounts" t1.getText();
try {
// Assume default encoding.
FileWriter fileWriter =
new FileWriter(fileName);
// Always wrap FileWriter in BufferedWriter.
BufferedWriter bufferedWriter =
new BufferedWriter(fileWriter);
// Note that write() does not automatically
// append a newline character.
bufferedWriter.write("Hello there,");
bufferedWriter.write(" here is some text.");
bufferedWriter.newLine();
bufferedWriter.write("We are writing");
bufferedWriter.write(" the text to the file.");
// Always close files.
bufferedWriter.close();
}
catch(IOException ex) {
System.out.println(
"Error writing to file '"
+ fileName + "'");
// Or we could just do this:
// ex.printStackTrace();
}
}
答案 0 :(得分:0)
注意Account末尾的斜杠和字符串之间的+以连接它们:
String fileName = "C:/Users/Brandon/Desktop/Java/Accounts/" + t1.getText();