-1

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

Jack Evans
  • 13
  • 5
  • 2
    Please include details about the errors (other than "multitude" and "strange"). – khelwood Jun 01 '16 at 09:14
  • Added @Khelwood "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." – Jack Evans Jun 01 '16 at 09:17
  • 1
    What do you think `new File ("Shadow.txt", "true")` is doing? – Thomas Jun 01 '16 at 09:18
  • You are reading and writing on the same file and appending the data which you have read before. Is there not any kind of concurrency problem? – wake-0 Jun 01 '16 at 09:19
  • Additionally have a look at`while ((data = br.readLine()) != null) { data = data+br.readLine();}` - you're assigning `data` multiple times and thus effectively overwrite it until it is null. Besides that you should _not_ use `br.readLine()` in the while condition _and_ the loop body. – Thomas Jun 01 '16 at 09:21
  • According to http://alvinalexander.com/java/edu/qanda/pjqa00009.shtml, the "true" uses the "append flag" @Thomas – Jack Evans Jun 01 '16 at 09:21
  • 2
    Read that tutorial again and pay attention to _where_ the flag is put. You don't put it into the `File` constructor but into the `FileWriter` constructor. - Didn't you find it strange that the tutorial uses a boolean (`true`) while you had to pass it as a string (`"true"`)? – Thomas Jun 01 '16 at 09:23
  • I've changed the code @Thomas and I still get errors.. You'll have to excuse my stupidity as I'm still in the process of teaching myself Java. – Jack Evans Jun 01 '16 at 09:31
  • Your while loop is still broken since you're checking `data` before assigning it a value. Besides that `data.equals(null)` will result in a NullPointerException is `data` _is_ null. Additionally `getResourceAsStream("Shadow.txt")` and `new File("Shadow.txt")` might refer to different files since the former depends on the classpath while the latter depends on the current working directory. – Thomas Jun 01 '16 at 09:35
  • Reading all this I get the impression that you're trying to leave out a few steps when learning Java or to make bigger leaps. Especially when starting keep your goals simple, i.e. learn how to use loops before using files, then use the file system before tampering with classpath resources etc. – Thomas Jun 01 '16 at 09:38
  • Here are two important lessons I'd add: 1) Learn to use a debugger, which will help you step through your code and see what it actually does. 2) When making statements like "I get errors" _always_ include information about the errors, i.e. _which_ errors, _where_ you get them etc. - a stacktrace might accomplish this already (just make sure to point at the right lines using the line numbers - we can't and won't count lines ourselves). – Thomas Jun 01 '16 at 09:39
  • Thanks @Thomas, I have assigned 'static String data = "Error"; static String dataString = "Error";' outside the function. The class path is also fine as it has affected the file. I do understand my Java isn't great, I learn the best by assigning myself a small project and learning how to complete that project, and this is one of the areas where this method of learning fails me, but 9/10 it works, and I enjoy it! I will look into using a debugger, and am just beginning to use these forums, I am sorry for being a nuisance! – Jack Evans Jun 01 '16 at 09:46
  • Assigning an initial value _might_ be fine but I'm not so sure in your case. Besides that you still want to swith reading a line and checking for null (take your initial version of the loop but add `data` to `dataString` in the body, e.g. like this: `String line; while ((line = br.readLine()) != null) { dataString += line; }` - Besides that try making `dataString` a `StringBuilder` for efficiency reasons (memory and runtime, especially if the file contains a lot of lines). – Thomas Jun 01 '16 at 09:58

1 Answers1

0

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();
}
kk.
  • 3,747
  • 12
  • 36
  • 67
  • Since he's trying to learn Java you should definitely add some explanation of what you're doing and why instead of just dumping code. – Thomas Jun 01 '16 at 09:59
  • I think I understand this, thanks Krishna for putting the code together and thanks a lot @Thomas for helping me and being considerate. :) Means a lot! – Jack Evans Jun 01 '16 at 10:35
  • @Thomas I guess he has given some kickstart to reading the file and writing to the file. While dumping the code I assumed that he knows what he is doing, I just tried to modify the code and dumped it with minimal changes. – kk. Jun 01 '16 at 15:11