Hi there I made a program that consist of jtextfield and couple jbuttons. I want to press a jbutton so that the jtextfields will be save to the computer. Any help will be useful.
I think this will help you..
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
if (jTxt_text.getText().isEmpty()) {
JOptionPane.showMessageDialog(rootPane, "Field is empty. Fill the filed and try again.");
} else {
//get the text from the jTextField and save it into a varibale.
String inputText = jTxt_text.getText();
//Where to save the file.
String savePath = "C:/test/sample.txt";
//Creating a file object, file is an abstract representation of file and directory pathnames.
File tempFile = new File(savePath);
//Check wther the file is available or not.
if (!tempFile.exists()) {
try {
//Creates the file if it's not exsising.
tempFile.createNewFile();
} catch (IOException ex) {
ex.printStackTrace();
}
}
try {
//writing process..
FileWriter tempWriter = new FileWriter(tempFile.getAbsoluteFile());
BufferedWriter tempBufferWriter = new BufferedWriter(tempWriter);
tempBufferWriter.write(inputText);
tempBufferWriter.close();
JOptionPane.showMessageDialog(rootPane, "Text file with the written text is successfully saved.");
jTxt_text.setText(null);
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
Still there's a small problem with this code tempBufferWriter.write(inputText) returns void so.. i don't know how to check wther the process completed successfully from the code itself..
Related
I have code that is generating data every second and displaying onscreen.
This all works fine but I want to create a log file of all the data to analyze later.
I can open/write/close a file each time data is created but I am unsure of how much processing power this is using as it is continually opening and closing the file
String data= reading1","+reading2+","+time +"/n";
try {
FileOutputStream out = openFileOutput("data.csv", Context.MODE_PRIVATE);
out.write(data.getBytes());
out.close();
} catch (Exception e) {
e.printStackTrace();
I would prefer to have the file open when the start button is clicked.
if ( v.getId() == R.id.start ){
// checks which button is clicked
Log.d("dennis", "Scan working"); //logs the text
// open a file
try {
FileOutputStream out = openFileOutput("data.csv", Context.MODE_PRIVATE);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
but when it comes to closing the file, no options for .close() appear when out is typed
if ( v.getId() == R.id.stop ){
// checks which button is clicked
out. // no valid options appear
messageValue.setText(R.string.stopButtonText);// changes the hallo world text
readNoRead=false;
}
Does all the open/write/close need to be together or is it possible to
***open file***
-----
Cycle through all the data
-----
***Close file***
You should store a link to your FileOutputStream on top level in your class.
Example to your code:
FileOutputStream out;
void clickStart() {
if (v.getId() == R.id.start){
// checks which button is clicked
Log.d("dennis", "Scan working"); //logs the text
// open a file
try {
out = openFileOutput("data.csv", Context.MODE_PRIVATE);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
void writeData() {
String data= reading1+","+reading2+","+time +"/n";
try {
out.write(data.getBytes());
} catch (IOException e) {
e.printStackTrace();
}
}
void clickStop() {
if (v.getId() == R.id.stop) {
try {
out.close();
} catch(IOException e) {
e.printStackTrace();
}
messageValue.setText(R.string.stopButtonText);// changes the hello world text
readNoRead=false;
}
}
It is definitely possible to open, process and close a file all in one block without closing the file.
Your out variable is not showing any method suggestions because it has not been defined in that block. Change the line
FileOutputStream out = openFileOutput("data.csv", CONTEXT.MODE_PRIVATE);
to
out = openFileOutput("data.csv", CONTEXT.MODE_PRIVATE);
and then add FileOutputStream out; to a line above the first if statement (outside of the block).
You may want to also look into 'try-catch-finally', or 'try with resources' as options for closing files in a try-catch block.
I'm trying to save user information in a single save file in local directory. However every time I run the app, the information doesn't save--I can tell by rerunning the app and the file data isn't updated or returning to the activity and finding out the data displayed isn't updated upon returning to the same activity. Here is the function in the activity where I set up a file output stream and decided to write in the information through a string containing all the User information and display "FILE CLOSED" once I assumed the file has written. Could you spot any missing steps or anything that I missed so that the file can be written?
public void saveToFile() throws FileNotFoundException{
//new filestream
FileOutputStream fostream;
fostream = openFileOutput(fileName, Context.MODE_PRIVATE);
//Write into file for each User in Array
for (int i = 0; i < userArrayList.size(); i++){
String contents = userArrayList.get(i).display();
System.out.println(userArrayList.get(i).display());
try {
fostream.write(contents.getBytes());
} catch (IOException e) {
System.out.println("NOTHING WRITTEN");
e.printStackTrace();
}
}
try {
fostream.close();
System.out.println("FILE CLOSED");
} catch (IOException e) {
e.printStackTrace();
}
}
Thanks so much for your help!
I followed this tutorial on how to create a simple text editor in Java, but the person who wrote the tutorial seems to have left out how to create a new file http://forum.codecall.net/topic/49721-simple-text-editor/
For the most part I was able to follow the guide, but I have no idea how one would create the 'New File' functionality.
you can write code like this to create new file :
try {
File file = new File("c:\\newfile.txt");
if (file.createNewFile()){
System.out.println("File is created!");
}else{
System.out.println("File already exists.");
}
} catch (IOException e) {
e.printStackTrace();
}
When you click on the save button on your text editor, include this in your actionPerformed() method -
FileDialog fd=new FileDialog(f1,"Save Your File",FileDialog.SAVE);
fd.setSize(400,200);
fd.setVisible(true);
try
{
FileWriter fw=new FileWriter(fd.getDirectory()+fd.getFile());
fw.write(t1.getText()); // t1 is the name of your textarea
fw.close();
}
catch(Exception e)
{
}
I want to read a file using jFileChooser. jFileChooser will come up after press of a button (say jbutton1ChooseFile) and select the required file. After the selection is complete, another button (say jbutton2) will be used to read the contents of the file which has just been selected by the user. So on clicking on jbutton2, selected file will be read.
I am posting few lines of code so that it would be easy to understand what I mean to say:
private void jButton1ChooseFileChooseFileActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
JFileChooser loadFile= new JFileChooser();
loadFile.setApproveButtonText("Select File");
loadFile.setAcceptAllFileFilterUsed(false);
FileNameExtensionFilter f1 = new FileNameExtensionFilter("Text Files", "txt", "text","rtf","doc","docx");
loadFile.setFileFilter(f1);
switch (loadFile.showOpenDialog(EncDecApp.this))
{
case JFileChooser.APPROVE_OPTION:
JOptionPane.showMessageDialog(EncDecApp.this, "Selection Successfull!",
"Attention!",
JOptionPane.OK_OPTION);
jButton1ChooseFile.setText("File Chosen");
jLabelChooseFile.setText(String.valueOf(loadFile.getSelectedFile()).substring(0,30)+"...");
fileSelect=true;
break;
case JFileChooser.CANCEL_OPTION:
JOptionPane.showMessageDialog(EncDecApp.this, "No file chosen",
"Attention!",
JOptionPane.OK_OPTION);
loadFile.setSelectedFile(null);
jButton1ChooseFile.setText("Browse..");
jLabelChooseFile.setText("Choose file to encrypt");
break;
case JFileChooser.ERROR_OPTION:
JOptionPane.showMessageDialog(EncDecApp.this, "Error",
"Choosing File",
JOptionPane.OK_OPTION);
loadFile.setSelectedFile(null);
jButton1ChooseFile.setText("Browse..");
jLabelChooseFile.setText("Choose file to encrypt");
}
loadFile.setVisible(true);
}
Upto this it's working perfectly.
Now, the code for jButton2 is as follows:
private void jButton2EncryptEncryptActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
//Charset charset=Charset.forName("UTF-8");
int returnVal=loadFile.showOpenDialog(jLabel1);
if(returnVal==loadFile.APPROVE_OPTION)
{
File filePath = loadFile.getSelectedFile();
try{
BufferedReader in = new BufferedReader(new FileReader(filePath));
String line = null;
while ((line = in.readLine()) != null) {
System.out.println(line);
jTextArea1.append(line + "\n");
}
in.close();
}
catch(IOException ex)
{
System.err.println("Open plaintext error: "+ex);
}
}
}
Any help will be highly appreciated.
At first glance the problem appears to be that you are using a local variable for the JFileChooser. That is to say, you have the line:
JFileChooser loadFile= new JFileChooser();
In your jButton1ChooseFileChooseFileActionPerformed function, and yet also try to refer to loadFile in your jButton2EncryptEncryptActionPerformed function.
In order to have the loadFile object available to both you need to have said loadFile object be a member of the class to which both functions belong.
I'm trying to make save files for a game i'm making, these files will have multiple txt files in them. My problem is that both the folder and the txt file wont create themselves in the directory I specify, here is the code for the folder:
File folde = new File("c:/Users/Mike/Desktop/Saves/bob/" + save);
try{
if (!folde.exists()) {
if (folde.mkdirs()) {
System.out.println("Created new save file");
} else {
System.out.println("Did not create new save file");
}
}
}finally{
System.out.println("Folder found.");
}
Here is the code for the file:
try{
PrintWriter writer = new PrintWriter("c:/Users/Mike/Desktop/javafiles/Saves/" + save + "/Stats.txt", "UTF-8");
writer.println(Stats.Health);
writer.println(Stats.Strength);
writer.println(Stats.Constitution);
writer.println(Stats.Dexterity);
writer.println(Stats.Inteligence);
writer.println(Stats.Wisdom);
writer.println(Stats.Charisma);
writer.close();
} catch (IOException x) {
System.err.println("Could not create save file.");
}
And here is the entire Class:
package files.maintain;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Scanner;
import vars.all.*;
public class SaveFile {
MainStart Start = new MainStart();
Stats Stats = new Stats();
public void save(){
Scanner in = new Scanner(System.in);
System.out.println("What should I save as?");
String save = in.nextLine();
File folde = new File("c:/Users/Dave/Desktop/Saves/bob/" + save);
try{
if (!folde.exists()) {
if (folde.mkdirs()) {
System.out.println("Created new save file");
} else {
System.out.println("Did not create new save file");
}
}
}finally{
System.out.println("Folder found.");
}
try{
PrintWriter writer = new PrintWriter("c:/Users/Dave/Desktop/javafiles/Saves/" + save + "/Stats.txt", "UTF-8");
writer.println(Stats.Health);
writer.println(Stats.Strength);
writer.println(Stats.Constitution);
writer.println(Stats.Dexterity);
writer.println(Stats.Inteligence);
writer.println(Stats.Wisdom);
writer.println(Stats.Charisma);
writer.close();
} catch (IOException x) {
System.err.println("Could not create save file.");
}
}
}
The Response i'm getting from the console is:
What should I save as?
bob
Folder found.
Could not create save file.*
My input is in bold,
I checked this website: http://www.mkyong.com/java/how-to-create-directory-in-java/
And the java tutorials: http://docs.oracle.com/javase/tutorial/essential/io/file.html
But that didn't work.
Thanks!
Make paths consistent if not the same. Instead of using string constants, use a single Java File object. You are using these 2 inconsistent prefixes:
"c:/Users/Dave/Desktop/Saves/bob/"
"c:/Users/Dave/Desktop/javafiles/Saves/"
Also, you need to improve your exception handling and reporting. Log as much information as you can about the original exception and the corrective (or emergency) action your program is taking.