0
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.

4
  • 3
    Add fw.close();
    – Elazar
    Commented Nov 12, 2017 at 12:51
  • What's the Owner class has to do with the question?
    – Elazar
    Commented Nov 12, 2017 at 12:52
  • Side note: You don't need everything to be static...
    – Juan
    Commented Nov 12, 2017 at 12:55
  • As @Elazar says just add fw.close() Commented Nov 12, 2017 at 13:12

3 Answers 3

2

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.

0
2

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,

  • fw.flush() - Call this when you want data you just wrote to be reflected in the actual file.
  • fw.close() - Call this when you are done writing all data that needs to be written by calling write method.
0
0

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.");
   }
}  
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.