I am trying to copy a text file but when the code finishes executing I only have the last line of text in the file. Obviously the scanLine() keeps overwriting the same line but I cant figure out to solve this problem. Any ideas?
do{
try{
FileWriter name = new FileWriter("/home/fok/Desktop/out");
BufferedWriter out = new BufferedWriter(name);
a=x.nextLine();scanner x grabs next line and sets it string a
out.write(a);//writes a to file
out.close();//closees file
} catch (IOException ioe){
System.out.println("file writer error");
}
} while(x.hasNext());
It is pretty simple, you are closing and opening the file inside the for loop.
public void readfile(){
try {
FileWriter name = new FileWriter("/home/fok/Desktop/out");
BufferedWriter out = new BufferedWriter(name);
do {
a=x.nextLine();scanner x grabs next line and sets it string a
out.write(a);//writes a to file
} while(x.hasNext());
out.close();//closees file
} catch (IOException ioe){
System.out.println("file writer error");
}
}
Related
I have this method that takes one String and writes it to a file. I set the PrintWriter to true because I want to save all the data that is written to it.
I want to have headings on this file. How can I write the headlines to the file and only do it one time?
My method looks like this:
public static void writeToFile(String text) {
try {
File f = new File("test.txt");
FileWriter writer = new FileWriter("test", true);
writer.write(text);
writer.close();
} catch (IOException ex) {
System.out.println(ex.getMessage());
}
}
It's not clear whether your file has multiple heading or not. Assuming your file has only one heading we can do this as follow -
1. Since your file contain heading only one time, you can check whether the file is accessing for the first time -
File f = new File(//your file name);
if(f.exists() && !f.isDirectory()) {
//write heading
}
2. If the file is first time accessed then you can add a header -
String heading = "Some heading";
The full code looks like -
public static void writeToFile(String text) {
String heading = "Some heading";
try {
File f = new File("test.txt");
FileWriter writer = new FileWriter(f, true);
if(f.exists() && !f.isDirectory()) {
writer.write(heading);
}
writer.write(text);
} catch (IOException ex) {
System.out.println(ex.getMessage());
}finally{
writer.close();
}
}
You can use BufferWriter to write a sentence and take a look at a better way to handle the file.
try {
String content = "This is the content to write into file";
File f = new File("test.txt");
// 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(content);
bw.close();
System.out.println("Done");
} catch (IOException e) {
e.printStackTrace();
}finally{
writer.close();
}
}
I have an application that creates a .txt file. I want to overwrite it. This is my function:
try{
String test = "Test string !";
File file = new File("src\\homeautomation\\data\\RoomData.txt");
// if file doesnt exists, then create it
if (!file.exists()) {
file.createNewFile();
}else{
}
FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
bw.write(test);
bw.close();
System.out.println("Done");
}catch(IOException e){
e.printStackTrace();
}
What should I put in the else clause, if the file exists, so it can be overwritten?
You don't need to do anything particular in the else clause. You can actually open a file with a Writer with two different modes :
default mode, which overwrites the whole file
append mode (specified in the constructor by a boolean set to true) which appends the new data to the existing one
You don't need to do anything, the default behavior is to overwrite.
No clue why I was downvoted, seriously... this code will always overwrite the file
try{
String test = "Test string !";
File file = new File("output.txt");
FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
bw.write(test);
bw.close();
System.out.println("Done");
}catch(IOException e){
e.printStackTrace();
}
Just call file.delete() in your else block. That should delete the file, if that's what you want.
FileWriter(String fileName, boolean append)
Constructs a FileWriter object given a file name with a boolean indicating whether or not to append the data written.
The Below one line code will help us to make the file empty.
FileUtils.write(new File("/your/file/path"), "")
The Below code will help us to delete the file .
try{
File file = new File("src\\homeautomation\\data\\RoomData.txt");
if(file.delete()){
System.out.println(file.getName() + " is deleted!");
}else{
System.out.println("Delete operation is failed.");
}
}catch(Exception e){
e.printStackTrace();
}
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).
I am developing a java application in which I need to save some data in a file. I tried to use different methods, however no file gets saved and I don't receive any errors. Here is my code for saving the file:
String filename = "/Users/name.txt";
FileWriter fstream;
try {
fstream = new FileWriter(filename);
BufferedWriter out = new BufferedWriter(fstream);
out.write("My Name is Bobby Bob");
out.newLine();
out.flush();
out.close();
}
catch (IOException e) {
e.printStackTrace();
}
I tried even making the file myself but it remains empty.
It's unlikely that you can write directly to the Users folder through Java on Mac OSX.
Try this to make sure:
String filename = "/Users/name.txt";
FileWriter fstream;
try {
File file = new File(filename);
// checking if we can write this file
System.out.println("Can write? " + file.canWrite());
fstream = new FileWriter(file);
BufferedWriter out = new BufferedWriter(fstream);
out.write("My Name is Bobby Bob");
out.newLine();
out.flush();
out.close();
} catch (IOException e) {
e.printStackTrace();
}
Output expected:
Can write? false
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!