2

Ok, before anyone starts flaming me for asking "dumb" questions, please note that I have pretty much exhausted every other option that I know of and come up empty handed. Still if you feel like it, please go ahead and downvote/report this question.

Now, for those that care

I am trying to take a String input from user and store it into a file Text.txt which will be created in the current working directory.

Following is the code

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.util.Scanner;


public class Encryption {

    public static void main(String[] args) throws Exception {

        System.out.println("Enter a String you wish to encrypt : ");
        new BufferedWriter(new FileWriter(".\\Text.txt")).write(new Scanner(System.in).nextLine());
        System.out.println("Done");
    }
}

My problem is, the file is getting generated at the correct destination, but is always empty. I have tried it on multiple JDK versions and on different machines. Still getting the blank text file.

Please tell me, what is it that I am doing wrong.

  • What are the other options that you tried? – Adelin Jul 18 '18 at 08:21
  • Before writting such oneliners, break them down into one function call at a time, and log the results, so that you understand what you're doing. – Adelin Jul 18 '18 at 08:22
  • PrintWriter and BufferedWriter were the 2 ways i know of, tried them, no difference in the op, about to try serialization (i know its wrong but i got nothing left) – 404 Brain Not Found Jul 18 '18 at 08:23

2 Answers2

4

You are not closing with .close() the BufferedWriter (which would then flush the last buffer and close the file).

You can however do that task in new style:

    Files.write(Paths.get(".\\Text.txt"),
                Arrays.asList(new Scanner(System.in).nextLine()),
                Charset.defaultCharset());

Otherwise you would need to introduce a variable, and gone is the one-liner.

Joop Eggen
  • 107,315
  • 7
  • 83
  • 138
  • Perfect, got it with `.close()`. I wasn't aware that `.close()` was this imperative to generate the op. I simply thought that i will leave the resource clean up to `gc()` by not writing the `.close()`. Thank You. Really Appreciate it – 404 Brain Not Found Jul 18 '18 at 08:32
1

Some changes i made your code to work

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.util.Scanner;


public class Encryption {

    public static void main(String[] args) throws Exception {

        System.out.println("Enter a String you wish to encrypt : ");
        String text = new Scanner(System.in).nextLine();
        BufferedWriter b = new BufferedWriter(new FileWriter(".\\Text.txt"));
        b.write(text);
        b.close();
        System.out.println("Done");
    }
}
CrazyProgrammer
  • 544
  • 8
  • 29