0

There is a class in Java called the PrintWriter where it can output the string into a file, which I found very easy to use since I only want to print strings. But now I want to take this file Strings and replace couple of words via code, how can I achieve that? is there any PrintReader class or similar?

Nathan Hughes
  • 94,330
  • 19
  • 181
  • 276
Naji Kadri
  • 89
  • 1
  • 1
  • 9
  • [`FileReader`](http://docs.oracle.com/javase/7/docs/api/java/io/FileReader.html), use it from the view of `BufferedReader` – jmj Jul 06 '15 at 16:19
  • [`Files.lines`](https://docs.oracle.com/javase/8/docs/api/java/nio/file/Files.html#lines-java.nio.file.Path-)? Your question isn't entirely clear. Not that you cannot replace words in a file without writing a new file with the replacements and then replacing the file. Well, you can - but it's really quite tricky. – Boris the Spider Jul 06 '15 at 16:20
  • @NajiKadri DontPrintReader? Just kidding. The java doc is your friend. [DontBeLazy](http://docs.oracle.com/javase/7/docs/api/java/io/package-summary.html). – Chetan Kinger Jul 06 '15 at 16:43

4 Answers4

4

For smaller files you can read all and write all using Files:

Path path = Paths.get("C:/Data/text.txt");
List<String> lines = Files.readAllLines(path, StandardCharsets.UTF_8);

Files.write(lines, StandardCharsets.UTF_8);

The above uses the Path class that is the more general successor of File.

Also a characterset is specified, here UTF-8, so you can combine all kinds of Unicode scripts, special symbols.

For Windows NotePad to recognize UTF-8 you can add a BOM as first character of the file (zero-width space):

lines.put(0, "\uFEFF", lines.get(0));

(With a bit more care of course.)

Nathan Hughes
  • 94,330
  • 19
  • 181
  • 276
Joop Eggen
  • 107,315
  • 7
  • 83
  • 138
2

There isn't anything called PrintReader. The BufferedReader class should pretty much do what you need.

http://docs.oracle.com/javase/7/docs/api/java/io/BufferedReader.html

1

Maybe you're looking for something like FileReader?

Yosef Weiner
  • 5,432
  • 1
  • 24
  • 37
1

You're probably looking for FileReader. Since you're trying to read a file, maybe you should take a look at reading-a-text-file-in-java.

Community
  • 1
  • 1