create a text file in java - java

I have a problem about creating a textfile with the name I want.
I want to create a textfile named : 'username' Subjects.
private void saveSubjects(){
RegisterFrame r = new RegisterFrame();
String username = r.txtUser.getText();;
try{
FileWriter f = new FileWriter(username + "" + "Subjects" + ".txt", true);
String subjects[] = lstSubjects.getItems();
for(int i = 0; i<subjects.length; i++){
f.write(subjects[i] + "\r\n");
}
f.close();
JOptionPane.showMessageDialog(null, "Data saved!", "Data Saved", JOptionPane.INFORMATION_MESSAGE);
}catch(Exception e){
JOptionPane.showMessageDialog(null, "Nothing Inputted!", "Error", JOptionPane.ERROR_MESSAGE);
}
}
I want to get the username from RegisterFrame as it is inputted there but it's not working.
I know it's a simple thing but I'm still a beginner in this. How can I solve this?
Thanks in advance

try this:
String username = r.txtUser.getText();
System.out.println("The loaded username is: " + username);
then you will see where your problem is : writing into the file OR getting the username text.
If the problem is in getting the text, consider other way of getting it or modify the question by removing the file write part and specifiing the username getting part.
Otherwise, IDK where the error is.
BTW: how is it not working? the file is not created at all? do you see any errors? the file has wrong name? please specify

Your code for writing the file seems to be fine. Based on your code I tried this which worked perfectly:
public static void main(String[] args) {
FileWriter f = null;
try {
f = new FileWriter("Subjects.txt", true);
String subjects[] = {"subject1", "subject2"};
for (String subject : subjects) {
f.write(subject + "\r\n");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
IOUtils.closeQuietly(f);
}
}
I'd say your problem is elsewhere.
Please note that best practice dictates that Closeable objects such as FileWriter should be closed in a finally block

Assuming new RegisterFrame() starts up a GUI window, the issue is your code runs before you have a chance to type in your name. Instead you need to use event listeners to capture the contents of text fields, otherwise the code to get the name runs immediately after the window opens, long before you have a chance to type anything in.
The timeline is like this:
RegisterFrame starts a new thread to display the GUI without blocking your code
Your code immediately pulls "" from txtUser, which is of course empty
Now you type your name in
Nothing happens, because nothing in your code is paying attention to that action
Instead, it should be:
RegisterFrame starts a new thread to display the GUI without blocking your code
The method returns, or starts doing work that isn't dependent on the GUI
Now you type your name in
An event listener is triggered from the new thread, and the associated action to get the name and write to a file is executed
You have to decide what sort of listener makes sense for your use case, for instance you might want to wait until the user clicks a button (that says "Submit" or "Write File" for instance) and register an ActionListener on that button. Then you put your username polling and file writing behavior in that action* and you're golden!
*I should add that in truth you want to do as little as possible in ActionListeners, and it would be better to check if the username is not empty, then pass the actual work off to another thread, for instance with a SwingWorker, but for your purposes I suspect it will be alright to not worry about that.

Related

Problems with setting text to a textField

I am creating a client-server chat application and I intend required to store the username for a better user experience.As soon as I fire the main method, the load() method is called.This method sets the user name automatically by reading from the configurations file.The configuration file is not null (I have the user name stored). But the textField is not updating.Any ideas?Here is my load method:
public static void load()
{
Properties prop = new Properties();
InputStream input = null;
try {
input = new FileInputStream("config.properties");
prop.load(input);
textField.setText(prop.getProperty("user")); //not updating!!!!
} catch (IOException ex) {
ex.printStackTrace();
} finally {
if (input != null) {
try {
input.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
Thanks for your help, guys.I figured out the problem.Actually, I had declared textfield as:
static JTextField textField=new JTextField();
outside main() and then again as:
textField=new JTextField();
inside the constructor.I removed the one inside the constructor and it solved the problem.
Once again thank you all for your help.
To add on to what Andreas Fester said above. You should first do a check on the file, if it exists or not, this will allow you to verify you are pointing to the right directory in the case the root of the project. Also add a clause saying something like if(prop.getProperty("user")==null){//handle null} then also try using textField.append("text"); just to see a different method and then verify by doing System.out.println("TextField: "+textField.getText()) to see if it is setting the text
If anything look at this demo given by oracle to use textfield. Also its a good practice to know when to separate member variable (belongs to instance) or class variables(static), I would avoid static like in the demo provided.
hope this helps.

Client-Server Java GUI: read/write causing program to freeze

I'm doing a client/server program in Java (including a GUI).
I've got the following code in the client:
public class SBListener implements ActionListener{
public void actionPerformed(ActionEvent e){
try{
outToServer.writeUTF(usn.getText().trim());
System.out.println("sent username to server");
playerExists = inToClient.readBoolean();
System.out.println("past getting player");
System.out.println("player exists = " + playerExists);
}catch(IOException a){
System.err.println(a);
}
if(playerExists == false){
JButton submitInfo = new JButton("submit info");
submitInfo.addActionListener(new SBNewInfoListener());
init.add(new JLabel(""));//dummy element to get the right alignment
init.add(new JLabel("First Name:"));
init.add(fn);
init.add(new JLabel("Last Name:"));
init.add(ln);
init.add(submitInfo);
add(init, BorderLayout.WEST);
init.setVisible(true);
init.revalidate();
init.repaint();
}
}
}
And the following code in the Server:
String username = inp.readUTF();
System.out.println(username);
out.writeBoolean(false);
System.out.println("wrote boolean, waiting for fn/ln/un");
fn = inp.readUTF();
System.out.println("got fn");
ln = inp.readUTF();
un = inp.readUTF();
But when the button that calls SBListener is clicked, the program freezes when it gets to the point where the Server is waiting for fn/ln/username. I added a bunch of system.out statements for debugging and I get up to the one that says "wrote boolean, waiting for fn/ln/un".
Basically, I'm trying to update the screen after the Server returns a false value. Specifically, I want to add two text fields for first & last name. I then want to send those values to the server.
Can anyone tell me how to fix this? Thanks in advance for any help!
Don't execute client/server code in an ActionListener. This will cause the Event Dispatch Thread to block while waiting for a response from the server. When EDT is blocked the whole GUI freezes.
Read the section from the Swing tutorial on Concurrency for more information. You need so use a separate Thread for the client/server code. Or you can use a SwingWorker as discussed in the tutorial.
My guess is that outToServer isn't being flushed. I would guess (although I can't tell from your sample code) that outToServer is a DataOutputStream. You need to call .flush to get the data out of the buffer and onto the wire.
Try this:
outToServer.writeUTF(usn.getText().trim());
outToServer.flush();

NFC with NFC-Tools, Creating NDEF Application

I am attempting to do what I would have guessed would be pretty simple, but as it turns out is not. I have an ACR122 NFC reader and a bunch of Mifare Classic and Mifare Ultralight tags, and all I want to do is read and write a mime-type and a short text string to each card from a Java application. Here's what I've got working so far:
I can connect to my reader and listen for tags
I can detect which type of tag is on the reader
On the Mifare Classic tags I can loop through all of the data on the tag (after programming the tag from my phone) and build an ascii string, but most of the data is "junk" data
I can determine whether or not there is an Application directory on the tag.
Here's my code for doing that:
Main:
public static void main(String[] args){
TerminalFactory factory = TerminalFactory.getDefault();
List<CardTerminal> terminals;
try{
TerminalHandler handler = new TerminalHandler();
terminals = factory.terminals().list();
CardTerminal cardTerminal = terminals.get(0);
AcsTerminal terminal = new AcsTerminal();
terminal.setCardTerminal(cardTerminal);
handler.addTerminal(terminal);
NfcAdapter adapter = new NfcAdapter(handler.getAvailableTerminal(), TerminalMode.INITIATOR);
adapter.registerTagListener(new CustomNDEFListener());
adapter.startListening();
System.in.read();
adapter.stopListening();
}
catch(IOException e){
}
catch(CardException e){
System.out.println("CardException: " + e.getMessage());
}
}
CustomNDEFListener:
public class CustomNDEFListener extends AbstractCardTool
{
#Override
public void doWithReaderWriter(MfClassicReaderWriter readerWriter)
throws IOException{
NdefMessageDecoder decoder = NdefContext.getNdefMessageDecoder();
MadKeyConfig config = MfConstants.NDEF_KEY_CONFIG;
if(readerWriter.hasApplicationDirectory()){
System.out.println("Application Directory Found!");
ApplicationDirectory directory = readerWriter.getApplicationDirectory();
}
else{
System.out.println("No Application Directory Found, creating one.");
readerWriter.createApplicationDirectory(config);
}
}
}
From here, I seem to be at a loss as for how to actually create and interact with an application. Once I can create the application and write Record objects to it, I should be able to write the data I need using the TextMimeRecord type, I just don't know how to get there. Any thoughts?
::Addendum::
Apparently there is no nfc-tools tag, and there probably should be. Would someone with enough rep be kind enough to create one and retag my question to include it?
::Second Addendum::
Also, I am willing to ditch NFC-Tools if someone can point me in the direction of a library that works for what I need, is well documented, and will run in a Windows environment.
Did you checked this library ? It is well written, how ever has poor documentation. Actually no more than JavaDoc.

Giving another class variablevalues before the variables are declared in Java

I am trying to pass values to variables that probably are not declared yet.
From my main source class I am giving another's class some values, but later on it seems like the values are gone.
Source code:
server.java (main):
public class server {
public static void main(String[] args) {
//Print a simple message to the user to notify there is something going on...
System.out.println("Starting server, please wait...");
//Connecting all class files to the server.
filehandler filehandlerclass = new filehandler();
networking networkingclass = new networking();
//End of class files connecting.
//Preparing the filehandler's file information to open a new filestream.
filehandlerclass.filetohandlename = "server";
filehandlerclass.filetohandleextention = "ini";
filehandlerclass.filetohandlepath = "configs\\";
//Request a new filestream using the filehandler's file variables.
filehandlerclass.openfilestream(filehandlerclass.filestream, filehandlerclass.filetohandle);
//Checks if the filehandler has tried to open a filestream.
if(filehandlerclass.filestreamopen == true) {
//Request a check if the filestream was opened sucessfully.
filehandlerclass.filestreamexists(filehandlerclass.filestream);
}
//If the filehandler has not tried to open a filestream...
else {
System.out.println("Error: The filehandler does not seem to have tried to open a filoestream yet.");
System.out.println("A possibility is that the server could not call the method from the filehandler properly.");
}
//Checks if the boolean "filestreamexists" from the filehandlerclass is true.
if(filehandlerclass.filestreamexists(filehandlerclass.filestream) == true) {
//The filestream seems to exist, let's read the file and extract it's information.
filehandlerclass.readfile(filehandlerclass.filestream);
}
else {
filehandlerclass.openfilestream(filehandlerclass.filestream, filehandlerclass.filetohandle);
}
}
}
filehandler.java:
//Imports the java.io library so the filehandler can read and write to text files.
import java.io.*;
public class filehandler {
//Variables for the filehandler class.
public String filetohandlename;
public String filetohandleextention;
public String filetohandlefullname = filetohandlename + "." + filetohandleextention;
public String filetohandlepath;
public String filetohandle = filetohandlepath + filetohandlefullname;
//Boolean that is true if the filehandler's "openfilestream"-method has tried to open a filestream.
//Is false as long as none filestreams have been touched.
public boolean filestreamopen = false;
//Declares a variable for the filestream to access text files.
public File filestream;
//End of variable list.
//Called to open a filestream so the server can load properties from text files.
public void openfilestream(File filestream, String filetohandle) {
//Tell the user that a filestream is about to be opened.
System.out.println("Opening filestream for \"" + filetohandlefullname + "\"...");
//Open a filestream called "filestream" using the variable "filetohandle"'s value
//as information about wich file to open the filestream for.
filestream = new File(filetohandle);
//Turn the boolean "filestreamopen" to true so next time the server checks it's
//value, it knows if the filehandler has tried to open a filestream.
filestreamopen = true;
}
//Boolean that checks if the filestream exists.
public boolean filestreamexists(File filestream) {
//Tell the user that a check on the filestream is going on.
System.out.println("Checking if filestream for \"" + filetohandlefullname + "\" exists...");
//If the filestream exists...
if(filestream.exists()) {
//Tell the user that the filestream exists.
System.out.println("Filestream for \"" + filetohandlefullname + "\" exists!");
//Make the boolean's value positive.
return true;
}
//If the filestream does not exist...
else {
//Tell the user that the filestream does not exist.
System.out.println("Filestream for \"" + filetohandlefullname + "\" does not exist!");
//Make the boolean's value negative.
return false;
}
}
//Called to read files and collect it's information.
public void readfile(File filestream) {
//Checks if the file that is going to be read is a configuration file.
if(filetohandleextention == "ini") {
//Tell the user that a configuration file is going to be read.
System.out.println("Extracting information from the configuration file \"" + filetohandle + "\".");
}
}
}
networking.java:
public class networking {
}
Problem:
server.java is going to serve commands to the source files and tell them what to do.
The source files are not going to act on their own unless server.java has given them a command.
This way I am planning to be able to write simple function calls in server.java to do greater tasks from the different source files.
server.java seems to pass the variables "filetohandlename", "filetohandleextention" and "filetohandlepath" before the variables are declared and when they get declared, they are declared with "null" as value.
Result:
I get no errors when I compile it.
All I think is happening is a miss match with giving the variables that specifies the file that is going to be read's proper values.
It also throws an exception which I have not been careing to look into for now, either it's because "null.null" does not exist or that I wrote the code wrong.
Final request:
Does anybody know if I can make a method for recieving the variables values
or if there is another more proper way around?
Could I probably make an array of the variables in server.java and collect the values from that array?
Thank you so much for your time.
This:
public String filetohandlename;
public String filetohandleextention;
public String filetohandlefullname = filetohandlename + "." + filetohandleextention;
initialises the first two variables to null, and the third to "null.null". Note that if you change one of the component variables that have made up filetohandlefullname, it won't then change the value of filetohandlefullname. If you want that to happen, then filetohandlefullname should be replaced by a method performing the appending operation.
This:
public void openfilestream(File filestream, String filetohandle)
passes a different variable filetohandle into the method. That variable is distinct from this.filetohandle.
I think there's a numberof issues with this code (above) and I'd do the following.
replace variables instantiated via other variables with methods that perform this dynamically. That way, when you change var1 that you'd expect to change the value of var2, that will happen automatically via a method return. e.g create a private method getFileToHandleFullName() and bin the corresponding variable
scope class members with this
where possible, make those members final so you don't inadvertently change them
This line
public String filetohandlefullname = filetohandlename + "." + filetohandleextention;
is executed when you instantiate the class (ie filehandler filehandlerclass = new filehandler();). At that point in time both variables are unset, thus filetohandlefullname is initialized to null.null
But there's a number of other problems with your code as well, like
//Request a new filestream using the filehandler's file variables.
filehandlerclass.openfilestream(filehandlerclass. filestream,filehandlerclass.filetohandle);
eg you're passing parameters that are fields from the same instance. That's totally useless as the method already has access to those, and it's very confusing.
And maybe slightly controversial:
//Make the boolean's value positive.
return true;
Comments are only useful if they clarify code that without them would be less obvious, and they have to be 100% true and not, as happens so often, what the program wishes the code would do. In this specific case neither of these conditions is fulfilled as the comment doesn't clarify what's going on, and actually the method's return value is set, not some nondescript "boolean's value"

How to Clear variables from JTextFields without closing whole program?

I have created a text file in which to store some variables which are taken from text fields. But in order to submit new variables to this text file, I need to close my program and reopen it. The dispose(); command closes the JFrame taking me to my main menu but upon opening the menu again and submitting different values, the values from the previous time have been resubmitted. Is there a simple way to amend this?
Here is my write to .txt code:
public class writeto {
static String data = AddProperty.inputdata;
BufferedWriter out;
public writeto(){
try{
out = new BufferedWriter(new FileWriter("writeto.txt", true));
out.write(data);
out.newLine();
out.close();
}catch(IOException e){
System.out.println("you have an error" + e);
}
}
}
and where the method is called in my addproperty class
submitproperty.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
housenumber1 = houseNumber.getText();
streetname1 = streetName.getText();
town1 = town.getText();
postcode1 = postcode.getText();
beds1 = beds.getText();
price1 = price.getText();
type1 = type.getText();
inputdata = housenumber1 + " " + streetname1 + " " + town1 + " " +
postcode1 +" " + beds1 + " " + price1 + " " + type1;
writeto write = new writeto();
dispose();
}
});
}
From your menu you should always create a new JFrame with new widgets (like text fields). A new text field has no content, if you show a text field again, it will still display it's previous content.
Additional remarks:
Please use standard naming conventions - not only when you show code to others. In your case: class names shall start with a capital letter, camel-case notation is preferred (writeto -> WriteTo)
The writeto class abuses the constructor. The code in your constructor does not create an writeto object but dumps some strings to a file. Put this kind of code to a method, not to a constructor.
The BufferedWriter will not be closed if an exception occurs. Look around at stackoverflow, a lot of questions/answers show the correct io-closeing pattern
disposing the jframe is a risk - the code is executed after pressing a button (correct?), inside a method on a button that is displayed on the frame (correct?). In that case the button may be disposed while a method on the button object is still executed.. Try setVisible(false) if you just want to hide the JFrame (like "close the dialog")
You would benefit greatly from using a database as opposed to a text file. Further your question displays a fundamental lack of knowledge of not only Swing, but basic CRUD (Create, Read, Update, Delete) functionality.
To answer your question you can clear your text field with textField1.setText("");
I would read up on using a database for storing data. It will make life much easier for you.

Categories

Resources