JTextArea to file - java

I want to save text from a JTextArea to a file, the code below works perfectly fine but the only thing is that the line breaks aren't converted. This means no matter how many lines I have in the JTextArea, they are all displayed in one line in the text file.
BufferedWriter writer = new BufferedWriter(new FileWriter(file));
writer.append(textArea.getText());
writer.close();
What should I do to fix this problem?

A decent solution is to use the Writer that comes with the JTextArea itself. Hang on,... example to come...
Edit Example below:
BufferedWriter writer = new BufferedWriter(new FileWriter(file, true)); // true for append
textArea.write(writer);
writer.close();

Related

Why this Java code do not write entire list on text file?

This java code prints text of all the webelements in console but when I write it on a text file, the output is a incomplete list. It do not write last 50-60 webelement text. What can be the reason ?
(I am using this code in selenium webdriver and the browser is Firefox.)
String TestFile = "D:\\temp.txt";
File FC = new File(TestFile);
FC.createNewFile();
FileWriter FW = new FileWriter(TestFile);
BufferedWriter BW = new BufferedWriter(FW);
List<WebElement> elementList = driver.findElements(By.className("someclassname"));
for(WebElement ele : elementList){
System.out.println(ele.getText());
BW.write(ele.getText());
BW.newLine();
}
You didn't close() the BW so the end of the text was left in the buffer.
Add to the end of this code
BW.close();

Unexpected result when writing a Unicode(UTF-8) text to file

I have problem when writing a Unicode(UTF-8) text to file with java.
I want writ some text in other language (Persian) to file in java, but i receive Unexpected result after run my app.
File file = new File(outputFileName);
FileOutputStream f = new FileOutputStream(outputFileName);
String encoding = "UTF-8";
OutputStreamWriter osw = new OutputStreamWriter(f,encoding);
BufferedWriter bw = new BufferedWriter(osw);
StringBuilder row = new StringBuilder();
row.append("Some text in English language");
// in below code it should be 4 space before علی
row.append(" علی");
// in below code it should be 6 space before علی یاری
row.append(" علی یاری");
bw.write(row.toString());
bw.flush(); bw.close();
how can i solve this problem?
The output is what is expected according to the Unicode bidirectional algorithm. The entire Persian text is rendered right-to-left. If you want the individual words to be laid out left-to-right, then you need to insert a strongly left-to-right character between the two Persian words. There's a special character for this: LEFT TO RIGHT MARK (U+200e). This modification to your code should produce the correct output:
row.append("Some text in English language");
row.append(" علی");
row.append('\u200e');
row.append(" علی یاری");

Replacing old content of a text file with new content when we write the file second time

Hi I am writing some data to a text file through java code but when i again run the code its again appending to the older data ,i want the new data to overwrite the older version.
can any one help..
BufferedWriter out1 = new BufferedWriter(new FileWriter("inValues.txt" , true));
for(String key: inout.keySet())
{
String val = inout.get(key);
out1.write(key+" , "+val+"\n");
}
out1.close();
code would help, but its likely you are telling it to append the data since the default is to overwrite. find something like:
file = new FileWriter("outfile.txt", true);
and change it to
file = new FileWriter("outfile.txt", false);
or just
file = new FileWriter("outfile.txt");
since the default is to overwrite, either should work.
based on your edit just change the true to false, or remove it, in the FileWriter. The 2nd parameter is not required and when true specifies that you want to append data to the file.
You mentioned a problem of incomplete writes... BufferedWriter() isn't required, if your file is smallish then you can use FileWriter() by itself and avoid any such issues. If you do use BufferedWriter() you need to .flush() it before you .close() it.
BufferedWriter out1 = new BufferedWriter(new FileWriter("inValues.txt"));
for(String key: inout.keySet())
{
String val = inout.get(key);
out1.write(key+" , "+val+"\n");
}
out1.flush();
out1.close();
Set append parameter to false
new FileWriter(yourFileLocation,false);
You can use simple File and FileWriter Class.
The Constructor of FileWrite Class provides 2 different varieties to make a file. One which only takes the Object of file. and another is with two parameters one with file object and second is boolean true/false which indicates whether file to be created is going to be append the contents or overwriting.
following code will do the overwriting of content.
public class WriteFile {
public static void main(String[] args) throws IOException {
File file= new File("new.txt");
FileWriter fw=new FileWriter(file,true);
try {
fw.write("This is first line");
fw.write("This is second line");
fw.write("This is third line");
fw.write("This is fourth line");
fw.write("This is fifth line");
fw.write("hello");
} catch (Exception e) {
} finally {
fw.flush();
fw.close();
}
}
}
It works same with PrintWriter class also, since it also provides 2 different varieties of Constructors same as FileWriter. But you can always refer to Java Doc API.

write output while loop of console to a text file in java

I am new to Java and I am stuck at this part :
I am trying to output the console output into a text file using JAVA .
But the problem is I have a While loop running and my code writes the output to the file but deletes the previous one .
I want to append the while loop output to file .
Any help is appreciated . Thanks In advance :)
PrintStream out = new PrintStream(new FileOutputStream("output.txt"));
System.setOut(out);
You need to append the new data to the previous data in the file, try this...
try{
File f = new File("d:\\t.txt");
FileWriter fw = new FileWriter(f,true); // true is for append
BufferedWriter bw = new BufferedWriter(fw);
bw.append(Your_data);
}catch(Exception ex){
ex.printStackTrace();
}
You should perform the redirection once, and before you do anything else. i.e. before you enter your loop.
Note (also) that your shell can redirect to a file, and that might be preferable to changing the destination of System.out. That's feasible but perhaps unexpected for someone who's going to debug your code in the future and wonder where their output is going...
Or perhaps consider a logging framework ?
Do it like this:
FileOutputStream fout=new FileOutputStream("output.txt",true);
while(condition)
{
PrintStream out = new PrintStream(new FileOutputStream("output.txt"));
System.setOut(out);
}
where second argument to FileOutputStream will open it in appendable mode.

How to empty file content and then append text multiple times

I have a file (file.txt), and I need to empty his current content, and then to append some text multiple times.
Example: file.txt current content is:
aaa
bbb
ccc
I want to remove this content, and then to append the first time:
ddd
The second time:
eee
And so on...
I tried this:
// empty the current content
fileOut = new FileWriter("file.txt");
fileOut.write("");
fileOut.close();
// append
fileOut = new FileWriter("file.txt", true);
// when I want to write something I just do this multiple times:
fileOut.write("text");
fileOut.flush();
This works fine, but it seems inefficient because I open the file 2 times just for remove the current content.
When you open up the file to write it with your new text, it will overwrite whatever is in the file already.
A good way to do this is
// empty the current content
fileOut = new FileWriter("file.txt");
fileOut.write("");
fileOut.append("all your text");
fileOut.close();
The first answer is not correct. If you create a new filewriter with the true flag for the second parameter, it will open in append mode. This will cause any write(string) commands to "append" text to the end of the file, not wipe out whatever text is already there.
I'm just stupid.
I only needed to do this:
// empty the current content
fileOut = new FileWriter("file.txt");
// when I want to write something I just do this multiple times:
fileOut.write("text");
fileOut.flush();
And AT THE END close the stream.
I see that this question was answered quite a few Java versions ago...
Starting from Java 1.7 and using the new FileWriter + BufferWriter + PrintWriter for appending (as recommended in this SO answer ), my suggestion for file erasing and then appending:
FileWriter fw = new FileWriter(myFilePath); //this erases previous content
fw = new FileWriter(myFilePath, true); //this reopens file for appending
BufferedWriter bw = new BufferedWriter(fw);
PrintWriter pw = new PrintWriter(bw);
pw.println("text");
//some code ...
pw.println("more text"); //appends more text
pw.flush();
pw.close();
Best I could think of is :
Files.newBufferedWriter(pathObject , StandardOpenOption.TRUNCATE_EXISTING);
and
Files.newInputStream(pathObject , StandardOpenOption.TRUNCATE_EXISTING);
In both the cases if the file specified in pathObject is writable, then that file will be truncated.
No need to call write() function. Above code is sufficient to empty/truncate a file.This is new in java 8.
Hope it Helps

Categories