lafeo_007
lafeo_007

Reputation: 76

FileWriter not working?

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

Answers (3)

Jayant Chauhan
Jayant Chauhan

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

Nibras Reeza
Nibras Reeza

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,

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

Upvotes: 2

xs0
xs0

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

Related Questions