I've create a GUI in Netbeans to get inputs from the user for certain fields. I don't understand how to save the text from the JTextField and Radio Buttons that are selected to a text file.
I attached the picture below of the user form.
Once "OK" button is pressed, the user gets a dialog to save the file.
Currently, I can save the file to a text file. But nothing appears in the text file. How can I retrieve data from each text field and radio button?
Please help, I've tried a lot of solutions but it has not been working properly.
private void buttonOkActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
try{
String filename = JOptionPane.showInputDialog(null, "Enter the name to be saved", "File Name", 1 );
FileOutputStream writer = new FileOutputStream(filename+".dat");
txtFirstName.getText().toString(); //Trying to get text from First Name field.
writer.close();
JOptionPane.showMessageDialog(null,"Saved Successfully");
}catch (Exception e) {
JOptionPane.showMessageDialog(null, e);
}
}
Between
FileOutputStream writer = new FileOutputStream(filename+".dat");
and
writer.close();
you should actually write using FileOutputStream's write method.
I think that what you want to do is:
FileOutputStream writer = null;
try {
FileOutputStream writer = new FileOutputStream(filename+".dat");
OutputStreamWriter os = new OutputStreamWriter(writer);
BufferedWriter bw = new BufferedWriter(os);
bw.write(txtFirstName.getText().toString());
} catch (FileNotFoundException ex) {
Logger.getLogger(generafechas.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(generafechas.class.getName()).log(Level.SEVERE, null, ex);
}finally{
if(writer!=null)
try {
writer.close();
} catch (IOException ex) {
Logger.getLogger(generafechas.class.getName()).log(Level.SEVERE, null, ex);
}
}
In the above code you can see that the FileOutputStream (conventionally references as fos for lazyness sake) gets wrapped.
There are two families of classes to write files in Java. Readers/Writers and Streams.
Your fos is a stream, so it deals with system specific implementation and writes bytes or integers, meanwhile that the BufferedWritter (bw for lazyness sake) deals with writing Objects, and basic types. With the wrapping we get the best of both worlds, high level handling and low level functionality.
Related
String pathSrc = "C:\\Users\\me\\Desktop\\somefile.pdf";
//should just check if file is opened by someone else
try
{
FileWriter fw = new FileWriter(pathSrc );
fw.close();
}
catch (IOException e)
{
System.out.println("File was already opened");
return;
}
This code should just check if pdf file is already opened. Instead after that code pdf file is corrupted. and can no longer be opened. Why is that?
Note that FileWriter starts empty everytime you instantiate a FileWriter with the Filename only, and then starts writing the data to the beginning of the file.
There's a second constructor that takes a boolean append flag that starts at the end of the file, appending data to the current file's contents.
This means that your code erases the whole pdf file and then close()s it, saving an empty PDF file, with zero bytes.
This simple change will fix your issue:
String pathSrc = "C:\\Users\\me\\Desktop\\somefile.pdf";
//should just check if file is opened by someone else
try {
FileWriter fw = new FileWriter(pathSrc, true);
fw.close();
}
catch (IOException e) {
System.out.println("File was already opened");
return;
}
I'm making a new game and I wanna make a coins collector to, later, buy things with those coins. I'm using eclipse.
void save() {
try {
PrintWriter out = new PrintWriter("coins.txt");
out.write(Integer.toString(nmonedas));
out.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
void load() {
StringBuffer texto=new StringBuffer();
try {
int c;
#SuppressWarnings("resource")
FileReader entrada=new FileReader("coins.txt");
while((c=entrada.read())!=-1){
texto.append((char)c);
}
}
catch (IOException ex) {}
labelshow.setText(texto.toString());
}
I have this code but i cant plus the info. NEED HELP PLS
Well, the thing is, I'm doing a game in eclipse and I want you to collect coins and keep them in a file.
They are collected perfectly and stored in the file, but when I start the game again I want them to be collected but they add up with the previous ones
I assume you are referring to appending text to a .TXT file. If so, you can use something like this:
Files.write(Paths.get("Path to text file here"), "Content".getBytes(), StandardOpenOption.APPEND);
I would put the above in a TRY CATCH block. Also look into PrintWriter as this may be more appopriate to what you need it for as it allows you to continuously write to the file.
How to read the object in to the file i am use the ObjectInputStream and ObjectOutputStream
class to read and write the Object of the my custom class Student for this demo.
Code to Write and read use::
try
{
if(af.filepath==null || af.filepath=="")//file path
{
JOptionPane.showMessageDialog(null, "Please Set File Path", "File Path Error", JOptionPane.ERROR_MESSAGE);
}
else
{
FileOutputStream fs=new FileOutputStream(af.filepath,true);
ObjectOutputStream fo=new ObjectOutputStream(fs);
fo.writeObject(af.s);//write the Super Class Object
fo.close();
}
}
catch (Exception ex)
{
System.out.println(ex);
}
---------------------------------------------------------------------------------
try
{
if(af.filepath==null || af.filepath=="")//file path have whole path of the file
{
JOptionPane.showMessageDialog(null, "Please Set File Path", "File Path Error", JOptionPane.ERROR_MESSAGE);
}
else
{
Student sp;
FileInputStream fs=new FileInputStream(af.filepath);
ObjectInputStream fo=new ObjectInputStream(fs);
while ((sp=(Student)fo.readObject())!=null)
{
sp.set();//for print object
}
fo.close();
}
}
catch (Exception ex)
{
ex.printStackTrace();
}
using this i am read first object in the file but after that raise an error
You have written one object and you are attempting to read multiple objects. When you attempt to read the second one, you are bound to get an exception.
If you want to read back an indefinite number of objects ... like that ... I suggest you write a null to the stream:
fo.writeObject(null);
(The javadoc doesn't say you can do this, but the Java Object Serialization spec says you can; see http://docs.oracle.com/javase/7/docs/platform/serialization/spec/output.html#933 ... step 3.)
The other problem (and this is what causes the corruption) is that you are attempting to append serialized objects to an existing file. That's not going to work. The serialization protocol says that a stream consists of a header followed by zero or more serialized objects ... and then the end of file. If you append one stream to another (e.g. FileOutputStream(path, true), the extra header is going to make the combined file readable at the point where the appended stuff starts.
I'm using Mallet through Java, and I can't work out how to evaluate new documents against an existing topic model which I have trained.
My initial code to generate my model is very similar to that in the Mallett Developers Guide for Topic Modelling, after which I simply save the model as a Java object. In a later process, I reload that Java object from file, add new instances via .addInstances() and would then like to evaluate only these new instances against the topics found in the original training set.
This stats.SE thread provides some high-level suggestions, but I can't see how to work them into the Mallet framework.
Any help much appreciated.
Inference is actually also listed in the example link provided in the question (the last few lines).
For anyone interested in the whole code for saving/loading the trained model and then using it for inferring model distribution for new documents - here are some snippets:
After model.estimate() has completed, you have the actual trained model so you can serialize it using a standard Java ObjectOutputStream (since ParallelTopicModel implements Serializable):
try {
FileOutputStream outFile = new FileOutputStream("model.ser");
ObjectOutputStream oos = new ObjectOutputStream(outFile);
oos.writeObject(model);
oos.close();
} catch (FileNotFoundException ex) {
// handle this error
} catch (IOException ex) {
// handle this error
}
Note though, when you infer, you need also to pass the new sentences (as Instance) through the same pipeline in order to pre-process it (tokenzie etc) thus, you need to also save the pipe-list (since we're using SerialPipe when can create an instance and then serialize it):
// initialize the pipelist (using in model training)
SerialPipes pipes = new SerialPipes(pipeList);
try {
FileOutputStream outFile = new FileOutputStream("pipes.ser");
ObjectOutputStream oos = new ObjectOutputStream(outFile);
oos.writeObject(pipes);
oos.close();
} catch (FileNotFoundException ex) {
// handle error
} catch (IOException ex) {
// handle error
}
In order to load the model/pipeline and use them for inference we need to de-serialize:
private static void InferByModel(String sentence) {
// define model and pipeline
ParallelTopicModel model = null;
SerialPipes pipes = null;
// load the model
try {
FileInputStream outFile = new FileInputStream("model.ser");
ObjectInputStream oos = new ObjectInputStream(outFile);
model = (ParallelTopicModel) oos.readObject();
} catch (IOException ex) {
System.out.println("Could not read model from file: " + ex);
} catch (ClassNotFoundException ex) {
System.out.println("Could not load the model: " + ex);
}
// load the pipeline
try {
FileInputStream outFile = new FileInputStream("pipes.ser");
ObjectInputStream oos = new ObjectInputStream(outFile);
pipes = (SerialPipes) oos.readObject();
} catch (IOException ex) {
System.out.println("Could not read pipes from file: " + ex);
} catch (ClassNotFoundException ex) {
System.out.println("Could not load the pipes: " + ex);
}
// if both are properly loaded
if (model != null && pipes != null){
// Create a new instance named "test instance" with empty target
// and source fields note we are using the pipes list here
InstanceList testing = new InstanceList(pipes);
testing.addThruPipe(
new Instance(sentence, null, "test instance", null));
// here we get an inferencer from our loaded model and use it
TopicInferencer inferencer = model.getInferencer();
double[] testProbabilities = inferencer
.getSampledDistribution(testing.get(0), 10, 1, 5);
System.out.println("0\t" + testProbabilities[0]);
}
}
For some reason I am not getting the exact same inference with the loaded model as with the original one - but this is a matter for another question (if anyone knows though, I'd be happy to hear)
And I've found the answer hidden in a slide-deck from Mallet's lead developer:
TopicInferencer inferencer = model.getInferencer();
double[] topicProbs = inferencer.getSampledDistribution(newInstance, 100, 10, 10);
I've been trying to open a text file and and save each line as the contents of an arraylist. Once this has been completed I would like to save it back to a file. I have been running into errors for so long and have tried numerous techniques. I found that for some reason, the files themselves are not being created. It may just be a simple error I'm overlooking but if you could provide any help I will be thankful.
Here's the code:
public void addToFile(){
File root = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/appName/savedlocations");
root.mkdirs();
File fileName = new File(root, "locationslatitude.txt");
File fileName2 = new File(root, "locationslongitude.txt");
String file = fileName.toString();
String file2 = fileName2.toString();
String theContent = Double.toString(currLatitude);
String theContent2 = Double.toString(currLongitude);
s = new Scanner(file);
while (s.hasNext()){
fileList.add(s.next());
}
s.close();
fileList.add(theContent);
s2 = new Scanner(file2);
while (s2.hasNext()){
fileList2.add(s2.next());
}
s2.close();
fileList2.add(theContent2);
try {//works for latitude file
FileWriter writer = new FileWriter(file);
for(String str: fileList) {
writer.write(str);
writer.write("\r\n");
}
writer.close();
} catch (java.io.IOException error) {
//do something if an IOException occurs.
Toast.makeText(this, "Cannot Save Back To A File", Toast.LENGTH_LONG).show();
}
//save the arraylist back to its appropriate file
try {//works for longitude file
FileWriter writer = new FileWriter(file2);
for(String str2: fileList2) {
writer.write(str2);
writer.write("\r\n");
}
writer.close();
} catch (java.io.IOException error) {
//do something if an IOException occurs.
Toast.makeText(this, "Cannot Save Back To A File", Toast.LENGTH_LONG).show();
}
}
I believe I found the answer to the problem and I wanted to post it back on here so if anyone else faces the same problem this might help them.
The problem was that it wasn't creating the file. The directory was created using "root.mkdirs();". However, the files were not created and I was trying to read from non-existing files. This is what I believe caused the error. So, in order to fix this problem I altered the code to this:
try{
s = new Scanner(fileName);
while (s.hasNext()){
fileList.add(s.next());
}
s.close();
fileList.add(theContent);
}catch (FileNotFoundException ex){
ex.printStackTrace();
try{
fileName.createNewFile();
}catch (IOException e){
e.printStackTrace();
Toast.makeText(this, "Hit IOException for file one", Toast.LENGTH_SHORT).show();
}
}
try{
s2 = new Scanner(fileName2);
while (s2.hasNext()){
fileList2.add(s2.next());
}
s2.close();
fileList2.add(theContent2);
}catch (FileNotFoundException ex){
ex.printStackTrace();
try{
fileName2.createNewFile();
}catch (IOException e){
e.printStackTrace();
Toast.makeText(this, "Hit IOException for file two", Toast.LENGTH_SHORT).show();
}
}
This was the only piece of code I had to alter. The code which saved back to the file worked. I hope this will be of use to someone and thanks everyone for your help.
This code works in my project. You can use it to save ArrayList contents to text file. Make sure that the directory is created beforehand. Just iterate through your list and use println method to write it to txt file.
FileWriter outFile = new FileWriter(Environment.getExternalStorageDirectory().getAbsolutePath() + "/appName/savedlocations/nameoftextfile.txt");
PrintWriter out = new PrintWriter(outFile);
out.println("PRINT LINES WITH ME");
out.print("NOT NECCESSARILY A NEW LINE");
out.close(); // at the very end
Do not forget to catch IOException.
Have you added the following permission in the AndroidManifest.xml?
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Check if the file directory etc exists on the device in the first place that you are using
/appName/savedlocations Good chance these do not exist. Wrong name for appName or savedLocations. Check this using some file explorer program. Tell us if it exists. Print out the full path name of
Environment.getExternalStorageDirectory().getAbsolutePath() + "/appName/savedlocations
and see if it really exists. Just download an app for file viewing or I think you can connect to the device via eclipse as well. If you need more info on how to do it let us know. But you should first check the actual error message and report this back.
don't invent your own serialization format. java already has that.
ArrayList<String> files = ...; // whatever
// write the object to a file
ObjectOutput out = new ObjectOutputStream(new FileOutputStream("filename.ser"));
out.writeObject(files);
out.close();
// read the object back
InputStream is = new FileInputStream("filename.ser");
ObjectInputStream ois = new ObjectInputStream(is);
ArrayList<String> newFiles = = (ArrayList)ois.readObject();
ois.close();