dimanche 28 juin 2015

How to edit an original text file and break the lines that reaches a maximum length. Java

I have a text file that I want to organize by setting a maximum length for each line to break and creates a new line afterwards. I know that I can open, read, and write on a file, but could I fix the same file without having to create a new file?

I tried writing different codes to do so, but I still have a little experience with IO API and I always confront a problem. This what I came up with so far without having any problems:

public static void main(String[] args) {
        File file = new File("data/test.txt");
        BufferedReader br = null;
        BufferedWriter bw = null;
        try {
            br = new BufferedReader(new FileReader(file));
            bw = new BufferedWriter(new FileWriter(file));
            final int MAX_LENGTH = 80;
            String line;
            while((line = br.readLine()) != null) {
                if(line.length() > MAX_LENGTH) {
                    //I want to break the line if it reached the MAX_LENGTH
                    //without overwriting data or skipping them
        } catch(IOException e) {

I would also appreciate any suggestions or ideas regarding my code.

Aucun commentaire:

Enregistrer un commentaire