Reputation: 76
import java.io.IOException;
import java.util.*;
public class Owner {
public static Scanner sc = new Scanner(System.in);
public static void main(String args[]) throws IOException {
String n = sc.nextLine();
Info.namec(n);
}
}
This is the second class, which is supposed to be printing the "HELLO" in the text file.
import java.io.*;
public class Info {
public static void namec(String n) throws IOException//name check
{
File f = new File("TEXT");
FileWriter fw = new FileWriter(f);
fw.write("HELLO!");
}
}
This code is not working, nothing is being typed in the text file. There are 2 classes, the "Hello" is not being printed.
Upvotes: 0
Views: 2589
Reputation: 173
Whenever you are using file writer it stores data on cache so you will require for flush and close file writer object.
Here i am adding sample code hope that will help you.
package com.testfilewriter;
import java.io.FileWriter;
public class FileWriterExample {
public static void main(String args[]) {
try {
FileWriter fw = new FileWriter("D:\\testfile.txt");
fw.write("Welcome to stack overflow.");
fw.close();
} catch (Exception e) {
System.out.println(e);
}
System.out.println("File writing complete.");
}
}
Upvotes: 0
Reputation: 127
Calling fw.write("String") alone does not guarantee data will be written to file. The data may simply be written to a cache and never get written to the actual file on disk.
I suggest you use below methods,
Upvotes: 2
Reputation: 2897
You don't close the file, and it looks like there is some buffering going on, so nothing gets to the file, as it's so short. Try this:
public static void namec(String n) throws IOException {
File f = new File("TEXT");
try (FileWriter fw = new FileWriter(f)) {
fw.write("HELLO!");
}
}
The so called try-with-resources statement will automatically close the stuff that gets opened in try()
, which is generally desirable.
Upvotes: 2