Search code examples
javafilereaderfile-handlinguppercasefilewriter

Convert text file data into uppercase in Java


I made the program in java to convert the text in the file in the uppercase but it erases data instead of converting it

But when I take data from 1 file and write converted data into another file, it works fine.

So I got problem that how can I do this using single file.

Here below is my code, Tell me how to correct this?

import java.io.FileReader;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.FileWriter;


public class uppercase{

    public static void main(String[] args) {
    
    try {
        FileReader reader = new FileReader("e.txt");
        FileWriter writer = new FileWriter("e.txt");

        int data;
        int data2;
        while((data=reader.read())!= -1) {
          data2=Character.toUpperCase(data);
          writer.write(data2);
        }
        reader.close();
        writer.close();

        
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
  }
}

Solution

  • firstly you open a stream to read from file and append the result to a String variable and at the end of reading, you write all the data to the file:

    try {
        FileReader reader = new FileReader("e.txt");
        String result = "";
        int data;
        int data2;
        while ((data = reader.read()) != -1) {
            data2 = Character.toUpperCase(data);
            result += (char)data2;
        }
        reader.close();
        System.out.println(result);
        FileWriter writer = new FileWriter("e.txt");
        writer.write(result);
        writer.flush();
        writer.close();
    
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }