> How can I output a .txt file in Java with a specific name depending on what the user has selected?

How can I output a .txt file in Java with a specific name depending on what the user has selected?

Posted at: 2014-12-18 
ry this...

import java.awt.*;

import java.awt.event.*;

import javax.swing.*;

import java.io.*;

public class Program extends JFrame implements ActionListener {

private JComboBox cbo;

private JButton btnSave;

public static void main(String[] args) {

new Program();

}

public Program() {

initialise();

}

private void initialise() {

JPanel pane = new JPanel();

String[] names = {"one", "two", "three"};

cbo = new JComboBox(names);

pane.add(cbo);

btnSave = new JButton("Save");

btnSave.addActionListener(this);

pane.add(btnSave);

getContentPane().add(pane);

setVisible(true);

setSize(300, 300);

setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE);

}

@Override

public void actionPerformed(ActionEvent ae) {

final String folder = "d:/temp";

String fileName = (String) cbo.getSelectedItem();

String path = String.format("%s/%s.txt", folder, fileName);

String content = "Content...";

saveTo(path, content);

// JOptionPane.showMessageDialog(null, path);

}

private void saveTo(String path, String content) {

File file = new File(path);

PrintWriter writer = null;

try {

writer = new PrintWriter(file);

writer.write(content);

writer.close();

} catch (IOException ex) {

ex.printStackTrace();

} finally {

if (writer != null) writer.close();

}

}

}

Never mind, figured it out.

Okay so I am writing a study program in java, and I want the user to be able to add vocabulary to certain subjects they created. I am using a JComboBox for the selection and basically this is what I did:

private void createFile(){

try{

subF = new FileWriter(new File(dir), true);

}

catch(Exception e){

e.printStackTrace();

}

}

And I put dir = "c:\\.mastertutor\\_subjects\\" + itemSelected + ".txt";

I know itemSelected is equal to what they have selected because I tested by printing it out to the console.

But when the file outputs it is name null.

Does anyone know how to fix this? Thank you for helping!