How to save multiple line from JTextArea to a File in Java - java

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

Related

Saving JTextArea using Bufferedwriter ignores new line. (Notepad clone) [duplicate]

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);

how to save jtextfield value to a .txt file as a log?

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();
}

How to Write text file Java

The following code does not produce a file (I can't see the file anywhere).
What is missing?
try {
//create a temporary file
String timeLog = new SimpleDateFormat("yyyyMMdd_HHmmss").format(
Calendar.getInstance().getTime());
File logFile=new File(timeLog);
BufferedWriter writer = new BufferedWriter(new FileWriter(logFile));
writer.write (string);
//Close writer
writer.close();
} catch(Exception e) {
e.printStackTrace();
}
I think your expectations and reality don't match (but when do they ever ;))
Basically, where you think the file is written and where the file is actually written are not equal (hmmm, perhaps I should write an if statement ;))
public class TestWriteFile {
public static void main(String[] args) {
BufferedWriter writer = null;
try {
//create a temporary file
String timeLog = new SimpleDateFormat("yyyyMMdd_HHmmss").format(Calendar.getInstance().getTime());
File logFile = new File(timeLog);
// This will output the full path where the file will be written to...
System.out.println(logFile.getCanonicalPath());
writer = new BufferedWriter(new FileWriter(logFile));
writer.write("Hello world!");
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
// Close the writer regardless of what happens...
writer.close();
} catch (Exception e) {
}
}
}
}
Also note that your example will overwrite any existing files. If you want to append the text to the file you should do the following instead:
writer = new BufferedWriter(new FileWriter(logFile, true));
I would like to add a bit more to MadProgrammer's Answer.
In case of multiple line writing, when executing the command
writer.write(string);
one may notice that the newline characters are omitted or skipped in the written file even though they appear during debugging or if the same text is printed onto the terminal with,
System.out.println("\n");
Thus, the whole text comes as one big chunk of text which is undesirable in most cases.
The newline character can be dependent on the platform, so it is better to get this character from the java system properties using
String newline = System.getProperty("line.separator");
and then using the newline variable instead of "\n". This will get the output in the way you want it.
In java 7 can now do
try(BufferedWriter w = ....)
{
w.write(...);
}
catch(IOException)
{
}
and w.close will be done automatically
It's not creating a file because you never actually created the file. You made an object for it. Creating an instance doesn't create the file.
File newFile = new File("directory", "fileName.txt");
You can do this to make a file:
newFile.createNewFile();
You can do this to make a folder:
newFile.mkdir();
Using java 8 LocalDateTime and java 7 try-with statement:
public class WriteFile {
public static void main(String[] args) {
String timeLog = DateTimeFormatter.ofPattern("yyyyMMdd_HHmmss").format(LocalDateTime.now());
File logFile = new File(timeLog);
try (BufferedWriter bw = new BufferedWriter(new FileWriter(logFile)))
{
System.out.println("File was written to: " + logFile.getCanonicalPath());
bw.write("Hello world!");
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
You can try a Java Library. FileUtils, It has many functions that write to Files.
It does work with me. Make sure that you append ".txt" next to timeLog. I used it in a simple program opened with Netbeans and it writes the program in the main folder (where builder and src folders are).
The easiest way for me is just like:
try {
FileWriter writer = new FileWriter("C:/Your/Absolute/Path/YourFile.txt");
writer.write("Wow, this is so easy!");
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
Useful tips & tricks:
Give it a certain path:
new FileWriter("C:/Your/Absolute/Path/YourFile.txt");
New line
writer.write("\r\n");
Append lines into existing txt
new FileWriter("log.txt");
Hope it works!

TextArea - Any way to get all text?

so I'm designing a text editor. For the Open/Save methods, I'm trying to use a TextArea (it doesn't have to be one, it's just my current method). Now, I have two problems right now:
1) When I load a file, it currently doesn't remove the contents currently in the text editor. For example, if I typed in "Owl", then loaded a file that contained "Rat", it would end up as "OwlRat". To solve this, I plan to use the replaceRange method (again however, it isn't absolute, any suggestions would be great!). However, I must replace all the contents of the text editor, not just selected text, and I can't figure out how to do that. Any tips?
2) Currently, when I load a file, nothing will happen unless I saved that file the same time I ran the application. So, for example, running the program, saving a file, closing the program, running the program again, and then loading the file will give nothing. I know this is because the String x doesn't carry over, but I can't think of anyway to fix it. Somebody suggested Vectors, but I don't see how they would help...
Here is the code for the Open/Save methods:
Open:
public void Open(String name){
File textFile = new File(name + ".txt.");
BufferedReader reader = null;
try
{
textArea.append(x);
reader = new BufferedReader( new FileReader( textFile));
reader.read();
}
catch ( IOException e)
{
}
finally
{
try
{
if (reader != null)
reader.close();
}
catch (IOException e)
{
}
}
}
Save:
public void Save(String name){
File textFile = new File(name + ".txt");
BufferedWriter writer = null;
try
{
writer = new BufferedWriter( new FileWriter(textFile));
writer.write(name);
x = textArea.getText();
}
catch ( IOException e)
{
}
finally
{
try
{
if ( writer != null)
writer.close( );
}
catch ( IOException e)
{
}
}
}
I had this same problem my guy friend, after much thought and research I even found a solution.
You can use the ArrayList to put all the contents of the TextArea and send as parameter by calling the save, as the writer just wrote string lines, then we use the "for" line by line to write our ArrayList in the end we will be content TextArea in txt file.
if something does not make sense, I'm sorry is google translator and I who do not speak English.
Watch the Windows Notepad, it does not always jump lines, and shows all in one line, use Wordpad ok.
private void SaveActionPerformed(java.awt.event.ActionEvent evt) {
String NameFile = Name.getText();
ArrayList< String > Text = new ArrayList< String >();
Text.add(TextArea.getText());
SaveFile(NameFile, Text);
}
public void SaveFile(String name, ArrayList< String> message) {
path = "C:\\Users\\Paulo Brito\\Desktop\\" + name + ".txt";
File file1 = new File(path);
try {
if (!file1.exists()) {
file1.createNewFile();
}
File[] files = file1.listFiles();
FileWriter fw = new FileWriter(file1, true);
BufferedWriter bw = new BufferedWriter(fw);
for (int i = 0; i < message.size(); i++) {
bw.write(message.get(i));
bw.newLine();
}
bw.close();
fw.close();
FileReader fr = new FileReader(file1);
BufferedReader br = new BufferedReader(fr);
fw = new FileWriter(file1, true);
bw = new BufferedWriter(fw);
while (br.ready()) {
String line = br.readLine();
System.out.println(line);
bw.write(line);
bw.newLine();
}
br.close();
fr.close();
} catch (IOException ex) {
ex.printStackTrace();
JOptionPane.showMessageDialog(null, "Error in" + ex);
}
There's a lot going on here...
What is 'x' (hint: it's not anything from the file!), and why are you appending it to the text area?
BufferedReader.read() returns one character, which is probably not what you're expecting. Try looping across readline().
Follow Dave Newton's advice to handle your exceptions and provide better names for your variables.
The text file will persist across multiple invocation of your program, so the lack of data has nothing to do with that.
Good luck.
Use textArea.setText(TEXT); rather than append; append means to add on to, so when you append text to a TextArea, you add that text to it. setText on the other hand will set the text, replacing the old text with the new one (which is what you want).
As far as why it's failing to read, you are not reading correctly. First of all, .read() just reads a single character (not what you want). Second, you don't appear to do anything with the returned results. Go somewhere (like here) to find out how to read the file properly, then take the returned string and do textArea.setText(readString);.
And like the others said, use e.printStackTrace(); in all of your catch blocks to make the error actually show up in your console.

how to append the written data to a file?

i am new developer in android.i would like to write some content to a file i have used a method to write into a file as follows
public void writeFile(String path,String text){
try{
Writer output = null;
File file = new File(path);
output = new BufferedWriter(new FileWriter(file));
output.write(text);
output.close();
System.out.println("Your file has been written");
}
catch (Exception e) {
e.printStackTrace();
}
here i am passing path of a file and text to write.if i use in this way i can write the data but the previous data is losing.
how can i append or insert the latest text into a file without losing previous text?
Thanks in advance
Try this. Change this line ...
output = new BufferedWriter(new FileWriter(file));
to
output = new BufferedWriter(new FileWriter(file, true));
The true indicates that you want to append not overwrite
Have a look here and try:
new FileWriter(file, true);
the boolean indicates whether or not to append to an existing file.

Categories

Resources