0

I am trying to write a program that takes content from one file and outputs it to another. I feel the code I wrote is really inefficient and can be improved with a loop somewhere, either when declaring variables or writing to the output file. Adding another loop is the only real concern I have. I know their are better ways to copy content from one file to another, but the way I chose works best for my understanding as being someone new to java.

    public void readFile() { 
      //File being read
      File file = new File("input.in");
      try 
      { 
          Scanner scnr = new Scanner(file); 
      while(scnr.hasNext()) 
      { 
          //Initializing/Declaring variable for each word on file input.in
          String contributions = scnr.next();
          String max = scnr.next();
          String min = scnr.next();
          String average = scnr.next();
          String total = scnr.next();
          try { 
              //output on file results.out
              File outputfile = new File("results.out"); 
              BufferedWriter bw = new BufferedWriter(new FileWriter(outputfile));
            //write each line
              bw.write(contributions);
              bw.newLine();
              bw.write(max);
              bw.newLine();
              bw.write(min);
              bw.newLine();
              bw.write(average);
              bw.newLine();
              bw.write(total);
              bw.close();             
          } 
          catch (IOException e) { // TODOAuto-generated 
              e.printStackTrace(); 
          } 
      }
      } 
      catch (FileNotFoundException e) 
      { // TODO Auto-generated
          e.printStackTrace(); 
      }
      }
ouflak
  • 2,458
  • 10
  • 44
  • 49
  • 2
    You can open and close the output file once, i.e. outside the loop. Other than that it looks pretty fine. If your output file's format is the same as the input file, you can use a [byte-level copying](https://stackoverflow.com/questions/43157/easy-way-to-write-contents-of-a-java-inputstream-to-an-outputstream). The general principle for copying large data is always something along the lines: allocate a buffer memory, read a small chunk in the buffer memory, write the buffer to output, repeat step 2 using the same buffer until there's nothing more to read. – ashu Feb 13 '22 at 05:25
  • Open both files outside the loop. For each line read, write it to the output file. Close both files when done. – Cheng Thao Feb 13 '22 at 06:09

0 Answers0