Search code examples
javastringreplacereadfilefilewriter

Replacing char which is different from specific values during reading file and writing to new file


I need to read text file, replace specific values like (a for 1, b for 2, c for 3) and if something different appears, exchange it for ascii_to_char(char_to_ascii(value)+1)), and then write it to another file. I managed to find a solution how to deal with a,b,c but I have no idea how to deal with something different. Here is my code

public void readAndWriteFromfile() throws IOException {
    BufferedReader inputStream = new BufferedReader(new FileReader(testFile));
    File newFile = new File(newTestFile);
    // if File doesnt exists, then create it
    if (!newFile.exists()) {
        newFile.createNewFile();
    }
    FileWriter filewriter = new FileWriter(newFile.getAbsoluteFile());
    BufferedWriter outputStream = new BufferedWriter(filewriter);
    String line;
    while ((line = inputStream.readLine()) != null) {
        outputStream.write(line.replaceAll("a", "1")
                .replaceAll("b", "2")
                .replaceAll("c", "3"));
    }
    outputStream.flush();
    outputStream.close();
    inputStream.close();
}

Solution

  • It would be better to implement separate method to encode the characters, for example, like this:

        private char encode(char c) {
            if (c >= 'a' && c <= 'c') {
                return (char)('1' + c - 'a');
            }
            return (char) (c + 1);
        }
    

    and call it for each character in the input file (except line feeds:)):

            String line;
            while ((line = inputStream.readLine()) != null) {
                char[] input = line.toCharArray();
                for (int i = 0; i < input.length; i++) {
                    input[i] = encode(input[i]);
                }
                outputStream.write(input);
                outputStream.append('\n');
            }