Android:Text after line break is not visible in a file(PrintWriter) - java

I am using PrintWriter to print some characters into the file. But when I use Println() to print a new line, the characters after new line are not visible.
Following is my code snippet
public void writeData(String data)
{
//PrintWriter csvWriter;
try
{
csvWriter = new PrintWriter(new FileWriter(file,true));
csvWriter.print(data+","+"hello");
//csvWriter.print("\r\n");
csvWriter.println();
csvWriter.print("world");
csvWriter.close();
}
catch (Exception e)
{
e.printStackTrace();
}
}
So in my file only the data & hello is visible. But "world" is not visible. I tried to print the new line using "\r\n" & "\n". But nothing is working.
Somebody please help me....Thanks!

try this:
csvWriter.println(System.getProperty("line.separator"));

Try using ... Line Seperator from system class
System.get("line.separator")

You have to flush data.
csvWriter.println();
csvWriter.print("world");
//writes data from buffer to stream
csvWriter.flush();
csvWriter.close();

try {
// open myfilename.txt for writing
OutputStreamWriter out = new OutputStreamWriter(FileOutputStream("myfilename.txt",0));
// write the contents on mySettings to the file
out.write("Hello \n World");
// close the file
out.close();
} catch (java.io.IOException e) {
//do something if an IOException occurs.
}

Related

Any explanation as to why Output Stream only prints the last line of the translated variable to a new file instead of all the lines?

I am trying to convert English words from a text file to a new file that translates the words into pig Latin. Everything translates the way it should when it is simply printed to the console but the issue I am having is that only the last line from the initial file appears on the new one.
public static void newFile(String pigLatin) {
OutputStream os = null;
try {
os = new FileOutputStream(new File("/Users/amie/Documents/inputnewnew.pig.txt"));
os.write(pigLatin.getBytes(), 0, pigLatin.length());
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
By default FileOutputStream is overriding the existing file. What you need to do is to use another constructor with append parameter
FileOutputStream(String name, boolean append)
like
os = new FileOutputStream(new File("/Users/...", true))
Take a look at the reference

Save to text file [duplicate]

In Java, I have text from a text field in a String variable called "text".
How can I save the contents of the "text" variable to a file?
If you're simply outputting text, rather than any binary data, the following will work:
PrintWriter out = new PrintWriter("filename.txt");
Then, write your String to it, just like you would to any output stream:
out.println(text);
You'll need exception handling, as ever. Be sure to call out.close() when you've finished writing.
If you are using Java 7 or later, you can use the "try-with-resources statement" which will automatically close your PrintStream when you are done with it (ie exit the block) like so:
try (PrintWriter out = new PrintWriter("filename.txt")) {
out.println(text);
}
You will still need to explicitly throw the java.io.FileNotFoundException as before.
Apache Commons IO contains some great methods for doing this, in particular FileUtils contains the following method:
static void writeStringToFile(File file, String data, Charset charset)
which allows you to write text to a file in one method call:
FileUtils.writeStringToFile(new File("test.txt"), "Hello File", Charset.forName("UTF-8"));
You might also want to consider specifying the encoding for the file as well.
In Java 7 you can do this:
String content = "Hello File!";
String path = "C:/a.txt";
Files.write( Paths.get(path), content.getBytes());
There is more info here:
http://www.drdobbs.com/jvm/java-se-7-new-file-io/231600403
Take a look at the Java File API
a quick example:
try (PrintStream out = new PrintStream(new FileOutputStream("filename.txt"))) {
out.print(text);
}
Just did something similar in my project. Use FileWriter will simplify part of your job. And here you can find nice tutorial.
BufferedWriter writer = null;
try
{
writer = new BufferedWriter( new FileWriter( yourfilename));
writer.write( yourstring);
}
catch ( IOException e)
{
}
finally
{
try
{
if ( writer != null)
writer.close( );
}
catch ( IOException e)
{
}
}
Use FileUtils.writeStringToFile() from Apache Commons IO. No need to reinvent this particular wheel.
In Java 11 the java.nio.file.Files class was extended by two new utility methods to write a string into a file. The first method (see JavaDoc here) uses the charset UTF-8 as default:
Files.writeString(Path.of("my", "path"), "My String");
And the second method (see JavaDoc here) allows to specify an individual charset:
Files.writeString(Path.of("my", "path"), "My String", StandardCharset.ISO_8859_1);
Both methods have an optional Varargs parameter for setting file handling options (see JavaDoc here). The following example would create a non-existing file or append the string to an existing one:
Files.writeString(Path.of("my", "path"), "String to append", StandardOpenOption.CREATE, StandardOpenOption.APPEND);
You can use the modify the code below to write your file from whatever class or function is handling the text. One wonders though why the world needs a new text editor...
import java.io.*;
public class Main {
public static void main(String[] args) {
try {
String str = "SomeMoreTextIsHere";
File newTextFile = new File("C:/thetextfile.txt");
FileWriter fw = new FileWriter(newTextFile);
fw.write(str);
fw.close();
} catch (IOException iox) {
//do stuff with exception
iox.printStackTrace();
}
}
}
I prefer to rely on libraries whenever possible for this sort of operation. This makes me less likely to accidentally omit an important step (like mistake wolfsnipes made above). Some libraries are suggested above, but my favorite for this kind of thing is Google Guava. Guava has a class called Files which works nicely for this task:
// This is where the file goes.
File destination = new File("file.txt");
// This line isn't needed, but is really useful
// if you're a beginner and don't know where your file is going to end up.
System.out.println(destination.getAbsolutePath());
try {
Files.write(text, destination, Charset.forName("UTF-8"));
} catch (IOException e) {
// Useful error handling here
}
Using Java 7:
public static void writeToFile(String text, String targetFilePath) throws IOException
{
Path targetPath = Paths.get(targetFilePath);
byte[] bytes = text.getBytes(StandardCharsets.UTF_8);
Files.write(targetPath, bytes, StandardOpenOption.CREATE);
}
In case if you need create text file based on one single string:
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
public class StringWriteSample {
public static void main(String[] args) {
String text = "This is text to be saved in file";
try {
Files.write(Paths.get("my-file.txt"), text.getBytes());
} catch (IOException e) {
e.printStackTrace();
}
}
}
Use Apache Commons IO api. Its simple
Use API as
FileUtils.writeStringToFile(new File("FileNameToWrite.txt"), "stringToWrite");
Maven Dependency
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.4</version>
</dependency>
Use this, it is very readable:
import java.nio.file.Files;
import java.nio.file.Paths;
Files.write(Paths.get(path), lines.getBytes(), StandardOpenOption.WRITE);
import java.io.*;
private void stringToFile( String text, String fileName )
{
try
{
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( text );
bw.close( );
//System.out.println("Done writing to " + fileName); //For testing
}
catch( IOException e )
{
System.out.println("Error: " + e);
e.printStackTrace( );
}
} //End method stringToFile
You can insert this method into your classes. If you are using this method in a class with a main method, change this class to static by adding the static key word. Either way you will need to import java.io.* to make it work otherwise File, FileWriter and BufferedWriter will not be recognized.
You could do this:
import java.io.*;
import java.util.*;
class WriteText
{
public static void main(String[] args)
{
try {
String text = "Your sample content to save in a text file.";
BufferedWriter out = new BufferedWriter(new FileWriter("sample.txt"));
out.write(text);
out.close();
}
catch (IOException e)
{
System.out.println("Exception ");
}
return ;
}
};
Using org.apache.commons.io.FileUtils:
FileUtils.writeStringToFile(new File("log.txt"), "my string", Charset.defaultCharset());
If you only care about pushing one block of text to file, this will overwrite it each time.
JFileChooser chooser = new JFileChooser();
int returnVal = chooser.showSaveDialog(this);
if (returnVal == JFileChooser.APPROVE_OPTION) {
FileOutputStream stream = null;
PrintStream out = null;
try {
File file = chooser.getSelectedFile();
stream = new FileOutputStream(file);
String text = "Your String goes here";
out = new PrintStream(stream);
out.print(text); //This will overwrite existing contents
} catch (Exception ex) {
//do something
} finally {
try {
if(stream!=null) stream.close();
if(out!=null) out.close();
} catch (Exception ex) {
//do something
}
}
}
This example allows the user to select a file using a file chooser.
Basically the same answer as here, but easy to copy/paste, and it just works ;-)
import java.io.FileWriter;
public void saveToFile(String data, String filename) {
try (
FileWriter fw = new FileWriter(filename)) {
fw.write(data);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
private static void generateFile(String stringToWrite, String outputFile) {
try {
FileWriter writer = new FileWriter(outputFile);
writer.append(stringToWrite);
writer.flush();
writer.close();
log.debug("New File is generated ==>"+outputFile);
} catch (Exception exp) {
log.error("Exception in generateFile ", exp);
}
}
It's better to close the writer/outputstream in a finally block, just in case something happen
finally{
if(writer != null){
try{
writer.flush();
writer.close();
}
catch(IOException ioe){
ioe.printStackTrace();
}
}
}
I think the best way is using Files.write(Path path, Iterable<? extends CharSequence> lines, OpenOption... options):
String text = "content";
Path path = Paths.get("path", "to", "file");
Files.write(path, Arrays.asList(text));
See javadoc:
Write lines of text to a file. Each line is a char sequence and is
written to the file in sequence with each line terminated by the
platform's line separator, as defined by the system property
line.separator. Characters are encoded into bytes using the specified
charset.
The options parameter specifies how the the file is created or opened.
If no options are present then this method works as if the CREATE,
TRUNCATE_EXISTING, and WRITE options are present. In other words, it
opens the file for writing, creating the file if it doesn't exist, or
initially truncating an existing regular-file to a size of 0. The
method ensures that the file is closed when all lines have been
written (or an I/O error or other runtime exception is thrown). If an
I/O error occurs then it may do so after the file has created or
truncated, or after some bytes have been written to the file.
Please note. I see people have already answered with Java's built-in Files.write, but what's special in my answer which nobody seems to mention is the overloaded version of the method which takes an Iterable of CharSequence (i.e. String), instead of a byte[] array, thus text.getBytes() is not required, which is a bit cleaner I think.
If you wish to keep the carriage return characters from the string into a file
here is an code example:
jLabel1 = new JLabel("Enter SQL Statements or SQL Commands:");
orderButton = new JButton("Execute");
textArea = new JTextArea();
...
// String captured from JTextArea()
orderButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
// When Execute button is pressed
String tempQuery = textArea.getText();
tempQuery = tempQuery.replaceAll("\n", "\r\n");
try (PrintStream out = new PrintStream(new FileOutputStream("C:/Temp/tempQuery.sql"))) {
out.print(tempQuery);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(tempQuery);
}
});
I have published a library that saves files, and handles everything with one line of code only, you can find it here along with its documentation
Github repository
and the answer to your question is so easy
String path = FileSaver
.get()
.save(string.getBytes(),"file.txt");
My way is based on stream due to running on all Android versions and needs of fecthing resources such as URL/URI, any suggestion is welcome.
As far as concerned, streams (InputStream and OutputStream) transfer binary data, when developer goes to write a string to a stream, must first convert it to bytes, or in other words encode it.
public boolean writeStringToFile(File file, String string, Charset charset) {
if (file == null) return false;
if (string == null) return false;
return writeBytesToFile(file, string.getBytes((charset == null) ? DEFAULT_CHARSET:charset));
}
public boolean writeBytesToFile(File file, byte[] data) {
if (file == null) return false;
if (data == null) return false;
FileOutputStream fos;
BufferedOutputStream bos;
try {
fos = new FileOutputStream(file);
bos = new BufferedOutputStream(fos);
bos.write(data, 0, data.length);
bos.flush();
bos.close();
fos.close();
} catch (IOException e) {
e.printStackTrace();
Logger.e("!!! IOException");
return false;
}
return true;
}

java how open file to write

I want to write a file but mixture of 3 bellow feature. how?
BufferedWriter , high volume data write needed
can append to exist text file
can set charset like "cp1256"
How mix all these features to open write file?
What you would do first is, Initiate your BufferedWriter :
`
String fileName = METHOD ARGUMENT, OR REGULAR STRING ("Output.txt");
BufferedWriter writer = null;
try {
File outFile = new File(fileName);
writer = new BufferedWriter(new FileWriter(OUTPUT NAME OF THE FILE YOU ARE WRITING. , true));
writer.write(WHAT YOU WANT TO WRITE TO THE FILE);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
// Close the writer regardless of what happens...
writer.close();
} catch (Exception e) {
}
Now to explain the code so I'm not just spoon feeding it to you.
When we declare the BufferedWriter writer = null; , we are setting it to null so that we don't write anything without setting a Try/Catch Exception Handler around it.
Once we are within our exception handled, we initiate a File called outFile. This will be the file we are outputting. The Argument we give it is the name of the file name. (A String Value such as, "Output.txt") NOTE: You MUST add the extension or else it won't work the way you are hoping it does.
Next, when we reference our BufferedWriter again, we initiate a new one in the try/catch handler, and inside we initiate a FileWriter (What will be doing the writing to the file). We give it two arguments. The name of the Output File("Output.txt"), and we also supply a true argument. What this does is makes the File Appendable! When we write true, we are saying we want the file to be appendable.
Finally, we write to the file, whatever it is you want to write.
As for the third feature, I don't think that FileWriter's will allow you to choose the Character Encoding that you want to write with, so unless you aren't using UTF-8, then you may want to use a PrintWriter
To do this, you would simply replace our `writer = new BufferedWriter(new FileWriter(OUTPUT NAME OF THE FILE YOU ARE WRITING. , true));
writer = new BufferedWriter(new PrintWriter(outputName, "UTF-8"));
I THINK this should work, if not, please let me know, I'll find a working solution.
public class WriteFile {
BufferedWriter out;
public void openFile(String file){
try {
out = new BufferedWriter(new FileWriter("data.txt"));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void writeInts(int[] ints){
try {
for(int i : ints) out.write(i+" ");
out.newLine();
out.flush();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void closeFile(){
try {
if (out!=null)out.close();
} catch (IOException e) {
}
}
}
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class Test {
public static void main(String[] args) throws IOException {
WriteFile wf = new WriteFile();
wf.openFile("test.txt");
wf.writeInts(new int[]{1,2,3,4,5});
wf.writeInts(new int[]{5,4,3,2,1});
wf.closeFile();
BufferedReader bf = new BufferedReader(new FileReader("test.txt"));
System.out.println(bf.readLine());
System.out.println(bf.readLine());
}
}
Output:
Line1: 1 2 3 4 5
Line2: 5 4 3 2 1

writing to a file, but not just at the end

I want to write something to a file line by line.
I have the problem, that this process takes a lot of time and get canceld sometimes. The current version write the stuff to the file just at the end. Is it possible to write it to the file line by line?
E.g. if I abboard after line 4 (of 400) the file currently is empty. But I want to have the 4 line already in the file.
Here is my code:
String path = args[0];
String filename = args[1];
BufferedReader bufRdr = // this does not matter
BufferedWriter out = null;
FileWriter fstream;
try {
fstream = new FileWriter(path + "Temp_" + filename);
out = new BufferedWriter(fstream);
} catch (IOException e) {
System.out.println(e.toString());
}
String line = null;
try {
while ((line = bufRdr.readLine()) != null) {
// HERE I'm doing the writing with out.write
out.write(...);
}
} catch (IOException e) {
System.out.println(e.toString());
}
try {
out.close();
} catch (IOException e) {
System.out.println(e.toString());
}
Use the flush function when you want to make sure the data that is already been written to the writer gets into the file
out.flush()
Try out.flush() after out.write(...)
Use out.flush() after calling out.write(...).
Considering the java documentation FileWriter, you can directly write things to a file using the FileWriter, without using a BufferedWriter.
Also, as pointed out, you need to flush your datas before closing your buffer. The function write only fill your buffer, but it doesn't write to the file on the disk. This operation is done by using flush or close (to write the current content of the buffer to the disk). The difference between these two functions is that flush let's you write things after and close closes the stream definitely.
The data you write to the buffer normally will not actually be written until out.flush() or out.close() is closed. so for your requirement you should use out.flush();

Simple PrintToFile program

I'm trying to write a simple java program in Eclipse that prints these four lines into a file "hello.txt". THe problem is, that nothing is happening, it doesn't create a new file, and if i make a file called "hello.txt" the program doesn't overwrite it. What am I doing wrong? Thanks for your answers. :)
import java.io.*;
public class output {
{
try{
PrintStream output = new PrintStream(new File("hello.txt"));
output.println("Hello World!");
output.println("this is ");
output.println("four lines of");
output.println("text.");
}catch(FileNotFoundException e){
System.out.println("Cannot write file!");
}
}
}
There are a few problems here:
you need to close your output stream when you're done with output.close();
Your class needs a main method void main(String[] args that calls the output routine
The output routine needs to be enclosed in a method
output.close();
or
output.flush();
If you don't close your streams, they won't be saved to disk.
I just run your code on windows putting it in main method and it works (it creates the file). try with an absolute path, perhaps you are checking the wrong directory.
You also should call
output.close();
you should add output.close();
try{
PrintStream output = new PrintStream(new File("hello.txt"));
output.println("Hello World!");
output.println("this is ");
output.println("four lines of");
output.println("text.");
output.close();
}catch(FileNotFoundException e){
System.out.println("Cannot write file!");
}
At first you have to create your file if it is not there. With that you create the PrintStream-Object and write the content you like in it. Finally don't forget to flush and close the stream.
try{
File f = new File("C:/hello.txt");
if (!f.exists()){
f.createNewFile();
}
PrintStream output = new PrintStream(f);
output.println("Hello World!");
output.println("this is ");
output.println("four lines of");
output.println("text.");
output.flush();
output.close();
}catch(FileNotFoundException e){
System.out.println("Fil kan ikke skrives!");
} catch (IOException e) {
e.printStackTrace();
}
The right way to do it is like this
import java.io.*;
class PrintStreamDemo {
public static void main(String args[]){
FileOutputStream out;
PrintStream ps; // declare a print stream object
try {
// Create a new file output stream
out = new FileOutputStream("myfile.txt");
// Connect print stream to the output stream
ps = new PrintStream(out);
ps.println ("This data is written to a file:");
System.err.println ("Write successfully");
ps.close();
} catch (Exception e){
System.err.println ("Error in writing to file");
}
}
}
you need to write output.close();

Categories

Resources