I am a novice. I am trying to take the user-input text from the JOptionPane, and store it into a text file. Thereafter I would like to read the text and do what-not with it.
May I please have help on storing the inputted text? Thanks.
Here's my code:
import javax.swing.JOptionPane;
import java.io.*;
public class RunProgram {
public static void introView() {
//The introduction
JOptionPane.showMessageDialog(null, "Welcome." +
" To begin, please click the below button to input some information " +
"about yourself.");
}
public static void personInput() {
try{
File userInfo = new File("C:\\Users\\WG Chasi\\workspace\\" +
"Useful Java\\products\\UserInfo.txt");
userInfo.getParentFile().mkdirs();
FileWriter input = new FileWriter(userInfo);
JOptionPane userInput = new JOptionPane();
userInput.showInputDialog("Enter details");/*I want to store the text from the InputDialog into the text file*/
//Write text from the JOptionPane into UserInfo.txt
}catch(Exception e){
JOptionPane.showMessageDialog(null, "An ERROR has occured.");
}
}
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
introView();
personInput();
}
});
}
}
You have any number of potential options, depending on your needs...
You could...
Write the contents to a Properties file...
private Properties properties = new Properties();
//...
String name = JOptionPane.showInputDialog("What is your name?");
properties.set("user.name", name);
//...
protected void savePropeties() throws IOException {
try (OutputStream os = new FileOutputStream(new File("User.properties"))) {
properties.store(os, "User details");
}
}
protected void loadPropeties() throws IOException {
try (InputStream is = new FileInputStream(new File("User.properties"))) {
// Note, this will overwrite any previously existing
// values...
properties.load(is);
}
}
As you can see, you have to physically load and save the contents yourself. This does mean, however, you get to control the location of the file...
You could...
Make use of the Preferences API...
String name = JOptionPane.showInputDialog("What is your name?");
Preferences preferences = Preferences.userNodeForPackage(RunProgram.class);
preferences.put("user.name", name);
Then you would simply use something like...
Preferences preferences = Preferences.userNodeForPackage(RunProgram.class);
String name = preferences.get("user.name", null);
to retrieve the values.
The benefit of this is the storage process is taking care for you, but you lose control of where the data is stored.
You could...
Write the data to a file yourself, in your own format. This is lot of work and overhead, but you gain the benefit of not only controlling the location of the file, but also the format that the data is maintained in. See Basic I/O for some more details.
Write the data in XML format, which provides a level of hierarchical control (if that's important), but does increase the complexity of the management.
Try this
public static void personInput()
{
String whatTheUserEntered = JOptionPane.showInputDialog("Enter details");
JFileChooser chooser = new JFileChooser();
chooser.setCurrentDirectory( new File( "./") );
int actionDialog = chooser.showSaveDialog(yourWindowName); //where the dialog should render
if (actionDialog == JFileChooser.APPROVE_OPTION)
{
File fileName = new File(chooser.getSelectedFile( ) + ".txt" ); //opens a filechooser dialog allowing you to choose where to store the file and appends the .txt mime type
if(fileName == null)
return;
if(fileName.exists()) //if filename already exists
{
actionDialog = JOptionPane.showConfirmDialog(yourWindowName,
"Replace existing file?");
if (actionDialog == JOptionPane.NO_OPTION) //open a new dialog to confirm the replacement file
return;
}
try
{
BufferedWriter out = new BufferedWriter(new FileWriter(fileName));
out.write(whatTheUserEntered );
out.close(); //write the data to the file and close, please refer to what madProgrammer has explained in the comments here about where the file may not close correctly.
}
catch(Exception ex)
{
System.err.println("Error: " + ex.getMessage());
}
}
}
I am basically attempting to get the text from the input dialog and write it to a file of your choice. The file will be written as a text file using the appending string ".txt" which sets the mime type so will always be text.
Let me know how it goes.
Related
Now, I read my .txt file by telling where is this file.
I want to change to I can select a file on my computer. How can I do that?
Scanner file = new Scanner(new File("Sample.txt"));
while (file.hasNextLine()) {
String input = file.nextLine();
}
Here is a runnable you can try. Like #Verity has stipulated, use the JFileChooser. Read the comments within the following code:
public class JFileChooserWithConsoleUse {
public static void main(String[] args) {
// A JFrame used here as a backbone for dialogs
javax.swing.JFrame iFrame = new javax.swing.JFrame();
iFrame.setDefaultCloseOperation(javax.swing.JFrame.DISPOSE_ON_CLOSE);
iFrame.setAlwaysOnTop(true);
iFrame.setLocationRelativeTo(null);
String selectedFile = null;
javax.swing.JFileChooser fc = new javax.swing.JFileChooser(new java.io.File("C:\\"));
fc.setDialogTitle("Locate And Select A File To Read...");
int userSelection = fc.showOpenDialog(iFrame);
// The following code will not run until the
// FileChooser dialog window is closed.
iFrame.dispose(); // Dispose of the JFrame.
if (userSelection == 0) {
selectedFile = fc.getSelectedFile().getPath();
}
// If no file was selected (dialog just closed) then
// get out of this method (which in this demo ultimately
// ends (closes) the application.
if (selectedFile == null) {
javax.swing.JOptionPane.showMessageDialog(iFrame, "No File Was Selected To Process!",
"No File Selected!", javax.swing.JOptionPane.WARNING_MESSAGE);
iFrame.dispose(); // Dispose of the JFrame.
return;
}
// Read the selected file... 'Try With Resources' is
// used here so as to auto-close the reader.
try (java.util.Scanner file = new java.util.Scanner(new java.io.File(selectedFile))) {
while (file.hasNextLine()) {
String input = file.nextLine();
// Display each read line in the Console Window.
System.out.println(input);
}
}
catch (java.io.FileNotFoundException ex) {
System.err.println(ex);
}
}
}
In this case you need to use an JFileChooser
I have been trying to compare the file content with user input. The program is reading from a specific file and it checks against the user's string input. I am having trouble comparing the ArrayList with the user input.
public class btnLoginListener implements Listener
{
#Override
public void handleEvent(Event arg0)
{
//variables for the class
username = txtUsername.getText();
password = txtPassword.getText();
MessageBox messageBox = new MessageBox(shell, SWT.OK);
try {
writeFile();
messageBox.setMessage("Success Writing the File!");
} catch (IOException x)
{
messageBox.setMessage("Something bad happened when writing the file!");
}
try {
readFile("in.txt");
} catch (IOException x)
{
messageBox.setMessage("Something bad happened when reading the file!" + x);
}
if (username.equals(names))
{
messageBox.setMessage("Correct");
}
else
{
messageBox.setMessage("Wrong");
}
messageBox.open();
}
}
private static void readFile(String fileName) throws IOException
{
//use . to get current directory
File dir = new File(".");
File fin = new File(dir.getCanonicalPath() + File.separator + fileName);
// Construct BufferedReader from FileReader
BufferedReader br = new BufferedReader(new FileReader(fin));
String line = null;
while ((line = br.readLine()) != null)
{
Collections.addAll(names, line);
}
br.close();
}
I am assuming you are trying to check whether an element exists in the list. If yes, then you need to use contains method, here's the Javadoc.
So, instead of using if (username.equals(names)), you can use if (names.contains(username)).
Apart from this, you should make the following changes:
Don't read the file every time an event is called. As you are reading a static file, you can read it once and store it in an ArrayList.
Make variables username and password local.
Remove writeFile() call unless it's appending/writing dynamic values on each event.
I am currently working on a small project to improve my programming skills, so not every “feature” might seem practical. Part of the application is a way to write notes and save them to a JList. While this notes-object is created, the content of the note (title and text) is saved to a .properties file. I picked the property-object because I needed some kind of key to allocate the content (text and title) to.
The Part for saving notes and creating the .properties file is working fine. But after closing and opening the application I want to populate the JList with the data in the .properties file. My problem now is that I want that the notes load in the same order as they were created in the first place. So if I create note a,b,c and close the application, I want that they load in this same order and I have a,b,c in my list again.
So I thought I’ll put the index of each file into the filename. This way the order in the notes directory on my hard disk is the same as in my JList. But this only works fine until you start deleting notes which messes up the order on the hard disk because of the id.
Can anyone give me a tip on how to solve this problem? I need a way to load the files in the same order they were created.
Here is the Code for adding notes:
private class AddNoteAction implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
// Initialize variables
Properties data = new Properties();
FileOutputStream oStream = null;
// Create instance of note with the given text
String text = fldText.getText();
String title = fldTitle.getText();
Note note = new Note(text, title);
// Create new file in notes directory to save properties data
File file = new File(Config.NOTES_DIR, note.getId() + title + ".properties");
// Save data from userinput to properties file (date and id are being set when a new note object is created)
data.setProperty("title", title);
data.setProperty("text", text);
data.setProperty("created", note.getDate());
data.setProperty("id", String.valueOf(note.getId()));
// Write data from properties to file on the drive
try {
oStream = new FileOutputStream(file);
data.store(oStream, Config.APP_NAME + " Notes Data");
} catch (IOException e1) {
e1.printStackTrace();
}finally {
if(!(oStream == null)){
try {
oStream.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
// Add note to model
noteListModel.addNote(note);
// Clear Textfields after adding Note
fldText.setText("");
fldTitle.requestFocusInWindow();
fldTitle.setText("");
}
}
Here is the code for loading the notes:
public class LoadNotes {
// Initialize Variables
private NoteListModel noteModel;
private File folder = new File(Config.NOTES_DIR);
private File[] files = folder.listFiles();
private Properties data = new Properties();
private FileInputStream iStream = null;
// Load ListModel when creating instance of this class
public LoadNotes(NoteListModel noteModel){
this.noteModel = noteModel;
}
// Load text-files data from notes directory into properties and create new note
public void load(){
for (File file : files){
if(file.isFile()){
try {
iStream = new FileInputStream(file);
data.load(iStream);
} catch (IOException e) {
e.printStackTrace();
}finally {
if(!(iStream == null)){
try {
iStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
// Read data from file to property
String title = data.getProperty("title");
String text = data.getProperty("text");
int id = Integer.parseInt((data.getProperty("id")));
// Create new note instance and save to model
Note note = new Note(text,title);
noteModel.addNote(note);
}
}
}
I am trying to make an application that will create Google Authenticator secret keys, as well as authenticate the OTP. I am writing all of my passwords to individual files titled with the name that goes along with them.
First and foremost, I am using this library.
https://github.com/aerogear/aerogear-otp-java
This is my code:
public void createUserFile(String name) throws IOException
{
File file = new File("users\\" + name + ".txt");
file.createNewFile();
}
public void generateUserKey(String name)
{
try
{
File file = new File("users\\" + name + ".txt");
FileWriter fw = new FileWriter(file);
BufferedWriter out = new BufferedWriter(fw);
String s = Base32.random();
out.write(s);
out.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
If I change the value of s to something like "Hello" I am fine. However, it will not write that random string. That is what I need help with. I have tinkered and searched hours for answers, and I have found nothing.
I don't believe you need createUserFile, and it isn't clear you necessarily know where the "users/" folder (a relative path) is. I suggest you use System.getProperty(String) to get user.home (the User home directory).
I would also suggest you use a try-with-resources Statement and a PrintStream. Something like
public void generateUserKey(String name) {
File file = new File(System.getProperty("user.home"), //
String.format("%s.txt", name));
try (PrintStream ps = new PrintStream(file)) {
ps.print(Base32.random());
} catch (IOException e) {
e.printStackTrace();
}
}
What im trying to do is simply letting the user choose a directory to save a text file to, Problem is im trying to select a folder im creating on my desktop but when i select the folder with the JFileChooser and letting the code i have do the work it's still saved outside the folder and into the desktop.. Why? Can someone please explain what i did wrong so i might learn something..
public class TextFileSaver {
String filePath;//Used in the setPath and getPath methods
String filename = File.separator+"tmp"; //Used for the JFileChoosers directory
public TextFileSaver(){
//Get our file saver to the screen
JFileChooser fc = new JFileChooser(new File(filename));
fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); //Only able to select directiories
// Show open dialog; this method does not return until the dialog is closed
fc.showSaveDialog(null);
File selectedLocation = fc.getCurrentDirectory(); //Gets the selected Location
//Sets the path of the file so we can read from it.
setPath(selectedLocation.getAbsolutePath());
FileName();
try {
SaveFile(filePath);
}
catch (IOException ex) {
Logger.getLogger(TextFileSaver.class.getName()).log(Level.SEVERE, null, ex);
//Show a message dialog
JOptionPane.showMessageDialog(null, "The file could not be saved, Please try again.",
"Error", JOptionPane.ERROR_MESSAGE);
}
}
public void setPath(String Path){
filePath = Path;
}
public String getPath(){
return filePath;
}
private void FileName(){
String name = JOptionPane.showInputDialog
("What name do you want to give the file?");
//Temporary code bellow will change to StringBuilder here.
filePath = filePath + "/" + name + ".txt";
}
private void SaveFile(String Path) throws IOException{
System.out.println(Path);
//The outStream that we will use to write to the text file the user is creating.
PrintWriter outStream = new PrintWriter(new BufferedWriter(new FileWriter(Path)));
outStream.println("Test text!");
outStream.close();
}
}
All the methods are executed through the constructor.. So the code happends step by step..
Use getSelectedFile() and not getCurrentDirectory() and also, you should append your filePath somewhere.