Java few errors while writing to text file? - java

I have a java assignment, and my last two errors are laid out in this code. For a little background, my code is taking input from a GUI and writing it into a text file. I realize you may need more code, and I will give more if needed, I just can't seem to understand these errors. Here is my code:
public void dataWriter(String data, String fileName) throws IOException
{
File file = getFileStreamPath(fileName);
if (!file.exists())
{
file.createNewFile();
}
try (FileOutputStream writer = openFileOutput(file.getName(), Context.MODE_PRIVATE)) // Error "cannot find symbol, variable MODE_PRIVATE"
{
for (String string = null, data)//error "variable data is already defined in dataWriter"
{
{
writer.write(string.getBytes());
writer.flush();
}
}
}
catch (Exception e)
{
}
}
Any help is greatly appreciated. Thank you so much!

From the original question it looks as though you are trying to write out to a file. OK, something like this should work:
public void dataWriter(String data, String fileName) throws IOException {
PrintWriter writer = new PrintWriter(new FileOutputStream(new File(fileName));
try {
writer.write(data);
} catch (Exception e) {
System.err.println("Some exception");
} finally {
writer.close();
}
The issue you were having with your above code was that the for loop syntax in Java is very different than how you originally stated.
Instead of for (String string = null, data)
An iterative for loop needs to look like this:
for (int i = 0; i < someDataStructure.size(); i++)
someDataStructure.get(i);
You could also do a for each loop if the Data Structure implements Iterable.
However, all this aside, you were attempting to iterate using a FileOutputStream when you had no List or Array over which to iterate, had you passed in another reference to a file or a list, the iteration should have looked something like this:
public void dataWriter(List data, String fileName) throws IOException {
PrintWriter writer = new PrintWriter(new FileOutputStream(new File(fileName));
try {
for (int i = 0; i < data.size(); i++)
writer.write(data);
} catch (Exception e) {
System.err.println("Some exception");
} finally {
writer.close();
}

Related

Java FileReader method is not returning/printing all characters in file record

I am trying to write to a file thru FileWriter and then read it thru FileReader. FileWriter writes the record to file okay, but the FileReader method appears to be skipping characters while printing. I have pasted the code and the file contents and output below. Can you please help identify what I might be missing or doing wrong?
***Update -
Just realized a possibility (after posting) that the "read()" in the while statement could be reading a Character ahead the "read()" in the print statement, and hence causing every other character (beginning with the first one) to skip the print statement. Not sure though. Could that be what is happening here?
Code -
public class FileIOCharClass {
public static void main(String[] args) {
File TestChar = new File("C:\\TestChar.txt");
FileIOCharClass FileIOChar = new FileIOCharClass();
try {
FileIOChar.charWriteMethod(TestChar);
}
catch (IOException a){
System.out.println("IO Exception occured in Write method");
}
try{
FileIOChar.charReadMethod(TestChar);
}
catch (IOException b){
System.out.println("IO Exception occured in Read method");
}
}
private void charWriteMethod(File CharFileToWrite) throws IOException {
FileWriter WriteRoutine = null;
try{
WriteRoutine = new FileWriter(CharFileToWrite);
WriteRoutine.write("Line-1");
WriteRoutine.write("Line-2");
WriteRoutine.write("Line-3");
}finally {
WriteRoutine.flush();
WriteRoutine.close();
}
}
private void charReadMethod(File CharFileToRead) throws IOException {
FileReader ReadRoutine = new FileReader(CharFileToRead);
while (ReadRoutine.read() != -1){
System.out.println(((char)ReadRoutine.read()));
}
}
}
Contents of TestChar file created -
Line-1Line-2Line-3
Program print output
i
e
1
i
e
2
i
e
3
Process finished with exit code 0
The issue is that you are reading twice. Once int the while condition, and another in the block statement
while (ReadRoutine.read() != -1){
System.out.println(((char)ReadRoutine.read()));
}
Instead you can try:
int data = ReadRoutine.read();
while (data != -1) {
System.out.println((char)data);
data = ReadRoutine.read();
}

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

Parse String Output to File

The first part of this “Frankenstein-ed” Java works perfectly, however the second part outputs some jumbled nonsense. So the variable of result will be my input from the user. I had to first UpperCase the string before I did the parsing for some dumb reason, it’s hard when you come from the Database/Analysis background and know you do something in seconds and not get an error... I gave credit where credit is due within the code...
myfile.txt ---> [Ljava.lang.String;#19821f
import java.io.*;
/*http://docs.oracle.com/javase/6/docs/api/java/lang/String.html#split%28java.lang.String%29*/
public class StringParser {
public static void main (String arg[])
throws FileNotFoundException {
String result = "eggs toast bacon bacon butter ice beer".toUpperCase();
String[] resultU = result.split("\\s");
String[] y = resultU;
{
for (int x=0; x< resultU.length; x++)
System.out.println(resultU[x]);
/*http://www.javacoffeebreak.com/java103/java103.html#output*/
FileOutputStream out; // declare a file output object
PrintStream p; // declare a print stream object
try
{
// Create a new file output stream
// connected to "myfile.txt"
out = new FileOutputStream("myfile.txt");
// Connect print stream to the output stream
p = new PrintStream( out );
p.println (resultU);
p.close();
}
catch (Exception e)
{
System.err.println ("Error writing to file");
}
}
}
}
Do you realize you're overwriting the same file for each element in your array?
You should use
out = new FileOutputStream("myfile.txt", true); // appends to existing file
As well as printing the actual element, not the String representation of the whole array
p.println(resultU[x]); // resultU without index prints the whole array - yuk!
Although you should probably update your code to only create the output File once and just write each element of the array to the same output stream, as the current method is a bit inefficient.
Something like
public static void main(String[] args) {
String result = "eggs toast bacon bacon butter ice beer".toUpperCase();
PrintStream p = null;
try {
p = new PrintStream(new FileOutputStream("myfile.txt"));
for (String s : result.split("\\s")) {
p.println(s);
p.flush(); // probably not necessary
}
} catch (Exception e) {
e.printStackTrace(); // should really use a logger instead!
} finally {
try {
p.close(); // wouldn't need this in Java 7!
} catch (Exception e) {
}
}
}
You have to iterate the array and write each element one after one.
FileOutputStream out; // declare a file output object
PrintStream p; // declare a print stream object
try
{
out = new FileOutputStream("myfile.txt");
p = new PrintStream( out );
for(String str:resultU)
{
p.println (str);
}
p.close();
}
catch (Exception e)
{
System.err.println ("Error writing to file");
}
Your line
p.println (resultU);
is printing a string representation of the array itself, not the elements in it. To print the elements, you'll need to loop through the array and print them out individually. The Arrays class has a convenience method to do this for you, of course.
That "jumbled non-sense" is the Strings location in memory, but that's not important right now.
The solution to your problem is this:
try {
FileOutputStream out = new FileOutputStream("myfile.txt", true);
PrintStream = new PrintStream(out);
for(String s : resultU)
p.println(s);
p.close();
} catch(Exception e) {
e.printStackTrace();
}
This replaces your entire for loop.

How do I save a String to a text file using Java?

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

Categories

Resources