I want to create a simple text file with some text in it.
import java.io.*;
class TextFileWriter{
public static void writeTextFile(String fileName, String s) {
FileWriter output = null;
try {
output = new FileWriter(fileName);
BufferedWriter writer = new BufferedWriter(output);
writer.write(s);
} catch (Exception e) {
throw new RuntimeException(e);
} finally {
if (output != null) {
try {
output.close();
} catch (IOException e) {
}
}
}
}
public static void main(String args[]){
writeTextFile("myText.txt","some text");
}
}
When i run this code i successfully create the text file but when i open it i don't see the contents ("some text"). What am I doing wrong?
You're closing underlying FileWriter but actual data are still stored (buffered) in BufferedWriter object. That's the object you have to close:
FileWriter output = new FileWriter(fileName);
BufferedWriter writer = new BufferedWriter(output);
writer.write(s);
writer.flush(); // Good practice but not required
writer.close();
Related
I ran over some problem with PrintWriter. I wrote some code that simply takes some input from a file and outputs it to another one.
Though a file is created, the file remains empty. The wanted input can be easily printed out in the console, which means the FileInputStream is working correctly.
Why is PrintWriter not printing anything?
public static void writeInFile(File in, File out) throws FileNotFoundException {
PrintWriter outputStream = null
Scanner scanner = new Scanner(new FileInputStream(in));
outputStream = new PrintWriter(new FileOutputStream(out));
outputStream.print("test");
while(scanner.hasNext()) {
outputStream.print(scanner.nextLine() + "\n");
}
scanner.close();
}
Make sure you always close your OutputStreams:
while(scanner.hasNext()) {
String s = scanner.nextLine();
outputStream.print(s+"\n");
System.out.println("Test "+s); //d.h. das Problem liegt am outputstream
}
outputStream.close();
scanner.close();
Edit: When you close the outputStream it calls flush automatically, which writes the buffer to the file. Without closing it the buffer may never be emptied/written to the file, as was the case here.
Also see this answer.
When dealing with IO which requires cleanup, I prefer to use auto resource cleanup. This is all you need at the most basic level:
public static void writeInToOut(InputStream in, OutputStream out) {
try(PrintWriter outputStream = new PrintWriter(out);
Scanner scanner = new Scanner(in)) {
while(scanner.hasNext()) {
outputStream.print(scanner.nextLine()+"\n");
}
}
}
You can now overload this function in several ways:
public static void writeInToOut(File file, OutputStream out) {
try (InputStream in = new FileInputStream(file)) {
writeInToOut(in, out);
} catch (IOException e) {
Logger.getAnonymousLogger().log(Level.WARNING, "IOError", e);
}
}
public static void writeInToOut(File inFile, File outFile) {
try (InputStream in = new FileInputStream(inFile);
OutputStream out = new FileOutputStream(outFile)) {
writeInToOut(in, out);
} catch (IOException e) {
Logger.getAnonymousLogger().log(Level.WARNING, "IOError", e);
}
}
public static void writeStdInToFile(File file) {
try (OutputStream out = new FileOutputStream(file)) {
writeInToOut(System.in, out);
} catch (IOException e) {
Logger.getAnonymousLogger().log(Level.WARNING, "IOError", e);
}
}
I have this code:
try {
File file = new File(something+counter+".txt");
counter++;
if (!file.exists()) {
file.createNewFile();
}
FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
bw.write(content);
bw.close();
} catch (IOException e) {
e.printStackTrace();
}
I need to make it like this: When they press enter, new file will be created in defined location (I made JTextField for this), but when they press it again, the file OVERWRITES. That's the problem. I need them to press enter - create new file: sample1.txt, press enter again, create new file: sample2.txt
OK by looking at your code now, it looks fine, but you probably declared the counter variable within the method. If so, it will be 'reset' to whatever you set it to every time the method is called.
EDIT:
This should work.
import java.io.*;
public class Example {
public static void main(String args[]) {
Example ex = new Example();
ex.writeFile();
ex.writeFile();
}
private void writeFile() {
try {
File file = new File("file" + counter + ".txt");
counter++;
System.out.println("Writing to " + file.toString());
if (!file.exists()) {
file.createNewFile();
}
FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
bw.write("content");
bw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
private int counter = 0;
}
I get
Writing to file0.txt
Writing to file1.txt
as output and both files have the string 'content' written in them.
EDIT2:
Call writefile whenever the user presses enter.
I am trying to make a text editor, but I am unable to save the contents to a text file : the file is created but empty.
class Saver implements ActionListener{
public void actionPerformed(ActionEvent e){
try{
File file = new File("projekat");
if(!file.exists()){
file.createNewFile();
FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
bw.write(tekst1);
bw.close();
}
}
catch(IOException ex){
ex.printStackTrace();
}
}
}
JTextArea code
area = new JTextArea(tekst1, 30,30);
tekst1 = area.getText();
Please help me. Best regards
The problem is that you need to call tekst1 = area.getText();
again in your actionPerformed method to update the contents of tekst1.
class Saver implements ActionListener {
public void actionPerformed(ActionEvent e) {
try {
File file = new File("projekat");
if (!file.exists()) {
file.createNewFile();
FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
// get latest contents of the JTextArea
tekst1 = area.getText();
bw.write(tekst1);
bw.close();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
bw.write(tekst1);
this line writes the content to the file.
you were close, the string you are writing is just empty, so it's normal that nothing writes to the file.
Some examples:
http://www.mkyong.com/java/how-to-write-to-file-in-java-bufferedwriter-example/
http://www.tutorialspoint.com/java/io/bufferedwriter_write_string.htm
http://beginnersbook.com/2014/01/how-to-write-to-file-in-java-using-bufferedwriter/
include only this code :---
file.createNewFile();
in your if statement and place other things out of your if.
I have the following code to write in three files. I have printed the Strings before writing to ensure they have some data in them, the printed Strings show the data given to them by calling this function but on creation of file the files are empty.
Please suggest something.
public static void save(String editedFileText,String srcFileText,String translFileText)throws IOException {
JFileChooser chooser = new JFileChooser();
System.out.println(editedFileText);
System.out.println(srcFileText);
System.out.println(translFileText);
int retrival = chooser.showSaveDialog(null);
if (retrival == JFileChooser.APPROVE_OPTION) {
try {
FileWriter edit = new FileWriter(chooser.getSelectedFile()+".txt");
edit.write(editedFileText.toString());
FileWriter srcFile = new FileWriter(chooser.getSelectedFile()+"_srcText"+".txt");
srcFile.write(srcFileText.toString());
FileWriter trans = new FileWriter(chooser.getSelectedFile()+"_translFile"+".txt");
trans.write(translFileText.toString());
} catch (Exception ex) {
ex.printStackTrace();
}
}
Get in the habit of creating all Writers, Readers, InputStreams and OutputStreams in try-with-resources statements. It ensures they will be properly closed:
try (FileWriter edit = new FileWriter(chooser.getSelectedFile()+".txt")) {
edit.write(editedFileText);
}
try (FileWriter srcFile = new FileWriter(chooser.getSelectedFile()+"_srcText"+".txt")) {
srcFile.write(srcFileText);
}
try (FileWriter trans = new FileWriter(chooser.getSelectedFile()+"_translFile"+".txt")) {
trans.write(translFileText);
}
If you're just writing a single String, you have the option of using Files.write, which allows you to forego the use of a Writer altogether:
Files.write(Paths.get(chooser.getSelectedFile()+".txt"),
editedFileText.getBytes());
Files.write(Paths.get(chooser.getSelectedFile()+"_srcText"+".txt"),
srcFileText.getBytes());
Files.write(Paths.get(chooser.getSelectedFile()+"_translFile"+".txt"),
translFileText.getBytes());
Add a finally to close the opened files, but first you need to declare them outside the try catch finally:
FileWriter edit,srcFile, trans;
edit = srcFile = trans = null;
try {
edit = new FileWriter(chooser.getSelectedFile()+".txt");
edit.write(editedFileText.toString());
srcFile = new FileWriter(chooser.getSelectedFile()+"_srcText"+".txt");
srcFile.write(srcFileText.toString());
trans = new FileWriter(chooser.getSelectedFile()+"_translFile"+".txt");
trans.write(translFileText.toString());
} catch (Exception ex) {
ex.printStackTrace();
}finally{
if(edit != null)
edit.close();
if(srcFile != null)
srcFile.close();
if(trans != null)
trans.close();
}
FileWriter writer=null;
try {
writer = new FileWriter(filename);
writer.write(sb.toString());
} catch (Exception e) {
} finally {
if (writer != null)
try {
writer.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
I have this code to write to a file when I add a user to an array list. The code works fine:
public void writeToFile(String content)
{
try {
File file = new File("H:/JavaWorkspace/TradingPlatformProject/User_Report.txt");
if (!file.exists()) {
file.createNewFile();
}
FileWriter fw = new FileWriter(file.getAbsoluteFile(), true);
BufferedWriter bw = new BufferedWriter(fw);
bw.write(content + "\n" );
bw.close();
logger.info("Recorded to User Activity file");
} catch (IOException e) {
e.printStackTrace();
}
}
I want to write to a separate file when a user does something differently (say, request a permission upgrade). Is there any way I can write to a new file "UserRequests.txt" without duplicating this code?
Why not make the method more general?
public void writeToFile(String content, String fileName, String path)
{
try {
File file = new File(path + fileName);
if (!file.exists()) {
file.createNewFile();
}
FileWriter fw = new FileWriter(file.getAbsoluteFile(), true);
BufferedWriter bw = new BufferedWriter(fw);
bw.write(content + "\n" );
bw.close();
logger.info("Recorded to User Activity file");
} catch (IOException e) {
e.printStackTrace();
}
}
Then you could use the method for writing all kinds of files :3
You should probably just use a 2nd argument, as in the following.
Moreover, you should close your Writers in a finally block. That way, you would be sure that the Writers are closed even if a exception occurred while writing.
public void writeToFile(String content, String path)
{
FileWriter fw
BufferedWriter bw
try {
File file = new File(path);
if (!file.exists()) {
file.createNewFile();
}
fw = new FileWriter(file.getAbsoluteFile(), true);
bw = new BufferedWriter(fw);
bw.write(content + "\n" );
bw.close();
logger.info("Recorded to User Activity file");
} catch (IOException e) {
e.printStackTrace();
} finally {
bw.close();
fw.close();
}
}
I would just pass in the file you want to write to:
public void writeToFile(String content, String filename){
And then:
File file = new File("H:/JavaWorkspace/TradingPlatformProject/"+filename);