When I open the newly written file in jGRASP, it contains many lines of text. When I open the same text file in notepad, it contains one line of text with the same data. The transFile is just a variable for the name of the text file that I am making.
FileWriter f = new FileWriter(transFile, true);
BufferedWriter out = new BufferedWriter(f);
out.write(someOutput + "\n");
out.close();
f.close();
I have changed the code to the following and it fixed the problem in notepad.
out.write(someOutput + "\r\n");
Why does this happen?
\r\n is the windows carriage return, which is what notepad will recognize. I'd suggest getting Notepad++ as it's just much much better.
The default line separator for windows (historically) is \r\n. The windows "notepad" app only recognizes that separator.
Java actually knows the default line separator for the system it's running on and makes it available via the system property line.separator. In your code you could do:
...
out.write(someOutput);
out.newLine();
...
the newLine() method appends the system's line separator as defined in that property.
You could do it this way also:
public void appendLineToFile(String filename, String someOutput) {
BufferedWriter bufferedWriter = null;
try {
//Construct the BufferedWriter object
bufferedWriter = new BufferedWriter(new FileWriter(filename));
//Start writing to the output stream
bufferedWriter.append( someOutput );
bufferedWriter.newLine();
} catch (FileNotFoundException ex) {
ex.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
} finally {
//Close the BufferedWriter
try {
if (bufferedWriter != null) {
bufferedWriter.flush();
bufferedWriter.close();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
Related
I have been encountering a problem for a while now, and have tested every possibility I can think of. Unfortunately, these possibilities did not work.
Basically, I am trying to write to a .txt file using BufferedWriter in Java. I need this setup so that I can have a line in between each piece of data. Imagine this is the text file produced from Java, it should look like this:
line1
line2
Here is my code:
public static void main(String[] args) {
Path path = Paths.get("test.txt");
if (!Files.exists(path)) {
try {
Files.createFile(path);
} catch (IOException e) {
System.out.println("Error in creating test.txt! Read the stacktrace
below.");
e.printStackTrace();
}
}
Charset charset = Charset.forName("UTF-8");
try (BufferedWriter writer = Files.newBufferedWriter(path, charset)) {
String string = "line1";
writer.write(string, 0, string.length());
writer.newLine();
writer.newLine();
writer.flush();
} catch (IOException e) {
System.out.println("Unable to write to file! Read the StackTrace below.");
e.printStackTrace();
}
try (BufferedWriter writer = Files.newBufferedWriter(path, charset)) {
String string = "line2";
writer.write(string, 0, string.length());
writer.flush();
} catch (IOException e) {
System.out.println("Unable to write to file! Read the StackTrace below.");
e.printStackTrace();
}
}
The output of this produces a text file as so:
line2
Now, I know I could just combine my two try/catches, and it would work. But this is just a test representation; in my real code, I need to do this separately so I can write in .txt files whenever specific events are triggered.
Basically, the newLine() methods are not saving unless I write text directly after them.
Any help is appreciated, as always!
The second BufferedWriter, or rather the second implicit FileWriter, overwrites the file created by the first one.
Combine the statements as you suggest, or use append mode (inefficient in this case).
How to write real time data to file in Java?
I'm trying to get real time twitter feed to text file. Here is a code that I have written:
public void onStatus(Status status)
{
User user = status.getUser();
BufferedWriter bufferedWriter = null;
try
{
bufferedWriter = new BufferedWriter(new FileWriter("c:\\twitterDumponFile.txt"));
String username = status.getUser().getScreenName();
bufferedWriter.write(username);
String profileLocation = user.getLocation();
bufferedWriter.write(profileLocation);
String content = status.getText();
bufferedWriter.write(content);
bufferedWriter.newLine();
}
catch (FileNotFoundException ex)
{
ex.printStackTrace();
}
catch (IOException ex)
{
ex.printStackTrace();
}
finally
{
//Closing the BufferedWriter
try
{
if (bufferedWriter != null)
{
bufferedWriter.flush();
bufferedWriter.close();
}
}
catch (IOException ex)
{
ex.printStackTrace();
}
}
}
When I open the file twitterDumponFile.txt it contains a single line of data. Everytime I open it it has a different data but a single line, it is not appending the new data on to the file.
Please help me where I'm getting wrong.
You need to open the FileWriter in append mode.
replace
bufferedWriter = new BufferedWriter(new FileWriter("c:\\twitterDumponFile.txt"));
by
bufferedWriter = new BufferedWriter(new FileWriter("c:\\twitterDumponFile.txt", true));
FileWriter("c:\\twitterDumponFile.txt")
This won't append the data to the file, it will write from the beginning of the file, use this instead :
FileWriter("c:\\twitterDumponFile.txt", true)
This will write to the end of the file rather than the beginning.
See the documentation of FileWriter.
You are overwriting the data already on the file instead of appending it.
Use API link to know how to append instead of overwriting...
It's always good way to use the api to know how and abouts of the methods and classes.
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!
i want to write some data to a .txt file.
public void writeToFile(String filename) {
try {
//Construct the BufferedWriter object
bufferedWriter = new BufferedWriter(new FileWriter(filename));
//Start writing to the output stream
bufferedWriter.write("first value : " + firstValue);
bufferedWriter.newLine();
} catch (FileNotFoundException ex) {
ex.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
} finally {
//Close the BufferedWriter
try {
if (bufferedWriter != null) {
bufferedWriter.flush();
bufferedWriter.close();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
i use this code, buth the problem is, that it overwrites the first line constantly (i think).
Does anyone have a idea how i can fix this?
i read everey 50ms a value from the serial port, and wan't to write this. (every value on a separate line)
it should write the values until i close the progam.
best regards
Try changing the line:
bufferedWriter = new BufferedWriter(new FileWriter(filename));
To:
bufferedWriter = new BufferedWriter(new FileWriter(filename, true));
I will open the FileWrite in Append mode, it is, it will add content in the file, and not overwrite it.
Open the writer like this:
bufferedWriter = new BufferedWriter(new FileWriter(filename, true));
That should open the file for appending. See javadoc.
I have one JTextArea and a Submit button in Java Swing.
Need 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.
try {
BufferedWriter fileOut = new BufferedWriter(new FileWriter("filename.txt"));
String myString1 =jTextArea1.getText();
String myString2 = myString1.replace("\r", "\n");
System.out.println(myString2);
fileOut.write(myString2);
fileOut.close();
} catch (IOException ioe) {
ioe.printStackTrace();
}
Please get me some suggestions
Why not use JTextArea's built in write function?
JTextArea area = ...
try (BufferedWriter fileOut = new BufferedWriter(new FileWriter(yourFile))) {
area.write(fileOut);
}
Replace all \r and \n with:
System.getProperty("line.separator")
This will make your code platform-independent and will write new lines to the files where necessary.
Edit: since you use BufferedWriter, you could also use the newLine() method
Why did you replace \r by \n ?
The line separator should be "\r\n".
This is what i thought up of :
public void actionPerformed(ActionEvent event) {
BufferedWriter writer;
try {
writer = new BufferedWriter(new FileWriter("SimpleText.txt",
false));
text.write(writer);
writer.close();
JOptionPane.showMessageDialog(null, "File has been saved","File Saved",JOptionPane.INFORMATION_MESSAGE);
// true for rewrite, false for override
} catch (IOException e) {
JOptionPane.showMessageDialog(null, "Error Occured");
e.printStackTrace();
}
}
Hope this helps