Search code examples
javafilewriterreaderbuffered

BufferedReader/Writer not working in Java


I'm trying to make two basic functions which will allow me to call them from other classes in order to return a HashMap from the 'getAllData()' and to write to the file in 'writeToFile()', without any luck. I've been tampering with it for a while now and just getting a multitude of strange errors.

Code:

    static HashMap<Integer ,String> getAllData(Integer choice) throws Exception{
    InputStream localInputStream = ClassLoader.getSystemClassLoader().getResourceAsStream("Shadow.txt");
    BufferedReader br = new BufferedReader(new InputStreamReader(localInputStream));
    if (choice.equals(1)){
        while ((!data.equals(null))){
            data = br.readLine();
            dataString = dataString+data;
        }
        writeToFile(dataString);
        br.close(); 
    }return name;
}

static void writeToFile(String data) throws IOException{;
    File file = new File ("Shadow.txt");
    FileWriter fileWriter = new FileWriter(file, true);
    BufferedWriter bw = new BufferedWriter(fileWriter);
    bw.write(data);
    bw.newLine();
    bw.flush();
    bw.close();
}

With this current code, nothing happens. The file remains exactly how it is, although to me, the code should read everything from it, and then append it.

How can I fix this? Thanks


Solution

  • This might help you:

    static void getAllData(final Integer choice) throws Exception {
        final BufferedReader br = new BufferedReader(new FileReader("Shadow.txt"));
        String data = "";
        final StringBuilder builder = new StringBuilder();
        if(choice.equals(1)) {
            while(data != null) {
                data = br.readLine();
                if(data != null) {
                    builder.append(data + "\n");
                }
            }
            writeToFile(builder.toString());
            br.close();
        }
    }
    
    static void writeToFile(final String data) throws IOException {
        final File file = new File("Shadow.txt");
        final FileWriter fileWriter = new FileWriter(file, true);
        final BufferedWriter bw = new BufferedWriter(fileWriter);
        bw.write(data);
        bw.flush();
        bw.close();
    }