JAVA - reading from a file and writing to another -


this question has answer here:

this code, can't make work properly, gets last line 3 lines total first text file , capitalize that, , cant figure out why

    import java.util.scanner;     import java.io.*;       public class allcapitals {     public static void main(string[] args) {         string readline;          string infilepath = "/home/file.txt";          string outfilepath = "/home/newfile.txt";           try (bufferedreader bufferedreader = new bufferedreader(new filereader(infilepath))) {          while ((readline = bufferedreader.readline()) != null) {             readline.touppercase();             string upperc = readline.touppercase();              system.out.println(upperc);              try (writer writer = new bufferedwriter(new outputstreamwriter(                     new fileoutputstream(outfilepath), "utf-8"))) {                     writer.write(upperc);                 }             }         } catch (ioexception e) {             system.out.println("error.");             e.printstacktrace();         }     } } 

edit: forgot functionallity.

i need read 3 lines normal text file goes that

    hello.     how ?     good, thank ! 

and output should in caps, last line "good thank you"

that's because recreate output file in each iteration while reading lines first. create output file once before start reading, example:

    try (bufferedreader bufferedreader = new bufferedreader(new filereader(infilepath));          writer writer = new bufferedwriter(new outputstreamwriter(new fileoutputstream(outfilepath), "utf-8"))     ) {         while ((readline = bufferedreader.readline()) != null) {             string upperc = readline.touppercase();             system.out.println(upperc);              writer.write(upperc);             writer.write(system.lineseparator());         }     } catch (ioexception e) {         system.out.println("error.");         e.printstacktrace();     } 

some other improvements:

  • removed pointless line readline.touppercase(); did nothing
  • add linebreak each line, otherwise uppercased content on same line

Comments