-1

I am writing to a file and I want to have the files name based on user input but save it in a different directory than where the .java file is located. Is there any code that does that? I am using Java. Here is my code:

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();
        }

  }
brandon Whe
  • 206
  • 1
  • 14

1 Answers1

0

Notice the slash at the end of Accounts and the + between the strings to concatenate them:

String fileName = "C:/Users/Brandon/Desktop/Java/Accounts/" + t1.getText();
Khary Mendez
  • 1,818
  • 1
  • 14
  • 18