I have a simple java shopping app with netbeans GUI, when someone presses the checkout jbutton I want to save jtextfield value to a external .txt file. everytime someone initiate the checkout option I want to save every transaction value to a .txt file with time. how can I do this ?
First get the text value of your JTextField by,
JTextField textField = ...; //
String text = textField.getText();
Then pass the value to the writeToFile method like below,
writeToFile(text);
writeToFile method
void writeToFile(String fileName, String text) throws Exception {
FileOutputStream out = new FileOutputStream(fileName, true);
out.write(text);
}
use this Code
String content = textFieldName.getText(); //step1: get the content of the textfield
try {
File file = new File("/users/mkyong/filename.txt");
// if file doesnt exists, then create it
if (!file.exists()) {
file.createNewFile();
}
FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
bw.write(content); //step2: write it
bw.close();
System.out.println("Done");
} catch (IOException e) {
e.printStackTrace();
}
Related
I'm making a simple notepad, which will save the content from JTextArea to a File. But i have a problem, i'm not able to save a multiline text.
Here's my code:
JTextArea textArea = new JTextArea();
File writeFile;
FileWriter fileWriter = null;
BufferedWriter bufWriter = null;
writeFile = new File("note.txt");
try {
fileWriter = new FileWriter(writeFile);
bufWriter = new BufferedWriter(fileWriter);
bufWriter.write(textArea.getText());
bufWriter.close();
} catch (IOException e) {
e.printStackTrace();
}
For example, i have a button and a textarea. When I input something like this:
test line 1
test line 2
and press the button to save, the file created. but the contents of the file, become like this
test line 1test line 2
Please give me a detail answer, so i can understand properly. i'm new in java GUI.
Thank you very much.
after trying your code, i see that your code only save the text in a single line. for example in the text area it's looked like this
first line
second line
third line
but in the file you just got
first linesecond linethird line
if that is the case you can use this code
File writeFile;
Writer writer = null;
writeFile = new File("D:\\note.txt");
try {
writer = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream(writeFile), "utf-8"));
jTextArea1.write(writer);
} catch (IOException ex) {
// report
} finally {
try {
writer.close();
} catch (Exception ex) {/*ignore*/
}
}
in this code we use writer from jtextarea itself, so it will save the text as we see at the jtextarea.
hope this help
I have to write the content of textarea into a file with line breaks. I got the output like, it is written as one string in the file.
public void actionPerformed(ActionEvent ev) {
text.setVisible(true);
String str= text.getText();
System.out.println(str);
try {
BufferedWriter fileOut = new BufferedWriter(new FileWriter("filename.txt"));
fileOut.write(str);
fileOut.close();
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
Example
Output should be:
I
am
King.
but it is showing:
IamKing.
Please get me some suggestions
Use JTextComponent.write(Writer):
Stores the contents of the model into the given stream. By default this will store the model as plain text.
E.G.
BufferedWriter writer = new BufferedWriter(new FileWriter("filename.txt"));
text.write(writer);
I have an application that creates a .txt file. I want to overwrite it. This is my function:
try{
String test = "Test string !";
File file = new File("src\\homeautomation\\data\\RoomData.txt");
// if file doesnt exists, then create it
if (!file.exists()) {
file.createNewFile();
}else{
}
FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
bw.write(test);
bw.close();
System.out.println("Done");
}catch(IOException e){
e.printStackTrace();
}
What should I put in the else clause, if the file exists, so it can be overwritten?
You don't need to do anything particular in the else clause. You can actually open a file with a Writer with two different modes :
default mode, which overwrites the whole file
append mode (specified in the constructor by a boolean set to true) which appends the new data to the existing one
You don't need to do anything, the default behavior is to overwrite.
No clue why I was downvoted, seriously... this code will always overwrite the file
try{
String test = "Test string !";
File file = new File("output.txt");
FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
bw.write(test);
bw.close();
System.out.println("Done");
}catch(IOException e){
e.printStackTrace();
}
Just call file.delete() in your else block. That should delete the file, if that's what you want.
FileWriter(String fileName, boolean append)
Constructs a FileWriter object given a file name with a boolean indicating whether or not to append the data written.
The Below one line code will help us to make the file empty.
FileUtils.write(new File("/your/file/path"), "")
The Below code will help us to delete the file .
try{
File file = new File("src\\homeautomation\\data\\RoomData.txt");
if(file.delete()){
System.out.println(file.getName() + " is deleted!");
}else{
System.out.println("Delete operation is failed.");
}
}catch(Exception e){
e.printStackTrace();
}
I'm having problems in my Java app. I wanted to transfer the texts in my JTextArea to a .txt file
for example
I inputted
"Hi
my name is george"
I want the outcome in my .txt file to be the same
but what happens is
"Himy name is george"
Here's my code
private void btnCreateActionPerformed(java.awt.event.ActionEvent evt) {
String filename,content;
String[] ArrContent=new String[9999];
int wordctr=0;
try
{
if(txtFilename.getText().isEmpty())
{
lblRequired.setText("Required Field");
}else
{
lblRequired.setText(" ");
filename=txtFilename.getText()+".txt";
FileWriter fw=new FileWriter(filename);
BufferedWriter writer = new BufferedWriter(fw);
if(txtContent.getText().contains("\r\n"))
writer.write("\r\n");
writer.write(txtContent.getText());
writer.close();
}
}
Try using JTextArea#write(Writer) instead...
String filename = txtFilename.getText()+".txt";
try (FileWriter fw = new FileWriter(new File(filename))) {
txtContent.write(fw);
} catch (IOException exp) {
exp.printStackTrace();
}
And make sure you making best efforts to close the resources that you create...
You need to use System.lineSeparator() to write a new line to a text file.
So try something like the following
if(txtContent.getText().contains("\r\n"))
writer.write(System.lineSeparator());
i have some text in TextArea, and i want to save it in file, my code is here:
private void SaveFile() {
try {
String content = txt.getText();
File file = new File(filename);
if (!file.exists()) {
file.createNewFile();
}
FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
bw.write(content);
bw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
but it saves without "\n"; and in new file everything is on one line;
ho can i foresee those "enters" too?
thank you in advance
the problem was because of notepad, so here is solution:
private void SaveFile() {
try {
String content = txt.getText();
content = content.replaceAll("(?!\\r)\\n", "\r\n");
File file = new File(filename);
// if file doesnt exists, then create it
if (!file.exists()) {
file.createNewFile();
}
FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
bw.write(content);
bw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
Thanks for helping
It should work. Try to use a text editor that display the line endings \r and \n and see what comes up.
If you want to be sure that the text file can be open by windows utilities like Notepad that only understand \r\n, you have to normalize it yourself this way:
content = content.replaceAll("(?!\\r)\\n", "\r\n");
This will replace all \n who is not preceded by a \r by the sequence \r\n.
You should use the read() and write() methods provided by the Swing text components. See Text and New Lines for more information.
If you want the output to contain a specific EOL string then you should use the following after creating the Document for your text component:
textComponent.getDocument().putProperty(DefaultEditorKit.EndOfLineStringProperty, "\r\n");
The \ character escapes the next character, as you say \n will create a newline. If you wish to output an actual \, you need to write:
"\n"
You can use a PrintWriter to print new Line to a file . On scanning TextArea's text if the TextArea's text contains "\\n" then use PrintWriter's println() method else make use of simply print() !
You have the content of your TextArea in a String. Now you can split it at newline, then you will get your String[]. Then you can iterate the String[] array and write it in your file:
private void SaveFile() {
try {
String content = txt.getText();
File file = new File(filename);
if (!file.exists()) {
file.createNewFile();
}
FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
for (String line : content.split("\\n")) {
bw.write(content);
}
bw.close();
} catch (IOException e) {
e.printStackTrace();
}
}