Jan Jan - 1 month ago 8
Java Question

Read file and convert all to UpperCase

I have a small problem. I am reading sort.txt in which there are words ordered like this:


  • a

  • b

  • c

  • asv

  • sad

  • dda



Below you can see my code which converts all of those to UPPERCASE. However I am getting following result:

ABCASVSADDDA

Which should be:


  • A

  • B

  • C

  • ASV



and so on

So as you can see it makes them UpperCase but why not every word in each line?

public class vlke_crke {


public static void main (String[] args) {
try
{
FileReader fr = new FileReader("sort.txt");
BufferedReader br = new BufferedReader(fr);
PrintWriter out = (new PrintWriter(new FileWriter("final.txt")));
String s="";
while((s = br.readLine()) != null)
{
out.write(s.toUpperCase()+"\n");

}
out.close();
}
catch(Exception e)
{
e.printStackTrace();
}
}

}

BzH BzH
Answer

Try

   while((s = br.readLine()) != null) 
   {
      out.println(s.toUpperCase());

    }

or

use "\r\n" instead of "\n" depending on system.

But better one is println() as it will take care of line separator that is used in system.