-1

I have this method that can read everything within a file but i need to be able to first add one whitespace before every new char at the beginning of everyline.

Tried to make it as easy as possible but non of it seem to work.

private static void write() throws IOException {

    FileWriter fw = new FileWriter("C:\\Users\\karwa\\Desktop\\HistoryOfProgramming.txt");

    for (int i = 0; i < 15; i++) {
        fw.write(" ");
    }

    fw.close();
}

Used bufferedReader aswell that had a whileloop that was reading every line and adding one whitespace for each line but that didn't work either. Ideas?

  • What are the contents of your file? Also how are you reading the file? It also looks like your aren't using the data you *read* to write the file again. – Nicholas K Jan 03 '19 at 14:20
  • Many words and some other chars + whitespaces. But it should be fine as long as i can add just one whitespace at the beginning of each line. – Axwell Smith Jan 03 '19 at 14:21
  • But also i would like to not use a specific count of lines. In this code i am actually only counting to 15 lines, i believe that it is count lines anyhow.. – Axwell Smith Jan 03 '19 at 14:23
  • 1
    What does " but non of it seem to work." mean? – nicomp Jan 03 '19 at 14:29
  • Your current code writes 15 consecutive spaces to a file, nothing more. What else have you tried? – f1sh Jan 03 '19 at 14:30
  • `FileWriter fw = new FileWriter("C:\\Users\\karwa\\Desktop\\HistoryOfProgramming.txt"); FileReader file = new FileReader("C:\\Users\\karwa\\Desktop\\HistoryOfProgramming.txt"); BufferedReader x = new BufferedReader(file); while (x.readLine() != null) { fw.write(" " + fw); } }` This is what i have tried. But this does the same exact thing as the first code... – Axwell Smith Jan 03 '19 at 14:31
  • @AxwellSmith that code cannot work correctly. What do you think `fw.write(" " + fw);` does? – f1sh Jan 03 '19 at 14:40

2 Answers2

3

you have to actualy read the lines and store them, only then can you add whitespace

public static void main(String... args) throws IOException {
    File file = new File("test.txt");

    Scanner fr = new Scanner(file);

    List<String> lines = new ArrayList<>();

    while (fr.hasNextLine()) {
        lines.add(fr.nextLine());
    }

    PrintStream fw = new PrintStream(file);

    for (String line : lines) {
        fw.println(" " + line);
    }

    fr.close();
    fw.close();
}
Louisb Boucquet
  • 311
  • 1
  • 9
3

Read/write the contents to a string Use replaceAll("\n", "\n ");

Jonas B
  • 2,351
  • 2
  • 18
  • 26