1

I have a file which every line contains strings like that :

usual,proper,complete,1,convenient,convenient,nonprob,recommended,recommend

I want to replace every word by such a code like that :

1000, 100, 110, 110, 111, 001, 111, 111, 1000

Here is the code that I used but it still incomplete :

public class Codage {
    BufferedReader in;

    public Codage() {
        try {
            in = new BufferedReader(new FileReader("nursery.txt"));
            FileOutputStream fos2 = new FileOutputStream("nursery.txt");
            DataOutputStream output = new DataOutputStream(fos2);
            String str;

            while (null != ((str = in.readLine()))) {

                String delims = ",";
                String[] tokens = str.split(delims);
                int tokenCount = tokens.length;
                for (int j = 0; j < tokenCount; j++) {
                    if (tokens[j].equals("usual")) {
                        tokens[j] = "1000";
                        output.writeChars(tokens[j]);

                    }
                    //continue the other cases
                }
                System.out.print(str);
            }

            in.close();

        } catch (IOException e) {

            System.out.println("There was a problem:" + e);
        }
    }

    public static void main(String[] args) {
        Codage c = new Codage();
    }

}

My code replace the values incorrectly.

13
  • 2
    How is the numeric code determined from the word? Commented Jun 19, 2015 at 0:22
  • Is there a patron to reference the numbers with the words? Commented Jun 19, 2015 at 0:25
  • Also, it is given to you any error? Or exception? Commented Jun 19, 2015 at 0:28
  • @hexafraction I will do it manually so I will make if structures Commented Jun 19, 2015 at 0:29
  • Why aren't you flushing the stream on exit? Commented Jun 19, 2015 at 0:30

1 Answer 1

3

First of all, the code you wrote here is not working, because when you open an outputStream to the exact file you try read from, it will empty the source file and the statement in.readLine() always returns null. So if this is your real code maybe this is the problem.

I assume that you know you should separate the file you are opening to read from and the one you want to write into. That is, when you open the nursery.txt to read from, you should create an outputStream to a temp file called nursery.tmp in the same path, and after the process is finished, you can delete the nursery.txt and rename the nursery.tmp to nursery.txt.

Also if I were you, I wouldn't do the job using if-else structure. It seams that you have unique keys like:

usual, proper, complete, convenient, convenient, nonprob, recommended, recommend

So maybe it is more convenient to use a map structure to lookup the replacing value:

usual, proper, complete, convenient, convenient, nonprob, recommended, recommend, ...

1000, 100, 110, 110, 111, 001, 111, 111, ...

But these are just some guesses and you know how to manage your business logic.

After that part I think this is a better idea to create the output data as String lines and write them line by line to the nursery.tmp:

public class Codage {

    private BufferedReader in;
    private BufferedWriter out;

    private HashMap<String, String> replacingValuesByKeys = new HashMap<String, String>();

    public Codage() {
        initialize();
    }

    private void initialize() {
        // I assumed that you have rule that a key like "proper" always goes to "100"
        // Initialize the map between keys and replacing values: 
        replacingValuesByKeys.put("usual", "1000");
        replacingValuesByKeys.put("proper", "100");
        replacingValuesByKeys.put("complete", "110");
        replacingValuesByKeys.put("convenient", "110");
        replacingValuesByKeys.put("nonprob", "111");
        replacingValuesByKeys.put("recommended", "001");
        replacingValuesByKeys.put("recommend", "1000");
    }

    public void doRelpacementInFile(){
        try {
            in = new BufferedReader(new FileReader("c:/nursery.txt"));
            out = new BufferedWriter(new FileWriter("c:/nursery.tmp"));

            String str = in.readLine();
            while (null != str) {
                Iterator<String> it = replacingValuesByKeys.keySet().iterator();
                while(it.hasNext())
                {
                    String toBeReplaced = it.next();
                    String replacementValue = replacingValuesByKeys.get(toBeReplaced);
                    // \\b is for word boundary, because you have both recommend and recommended
                    //        and we do not want to replacing the [recommend] part of recommended.
                    str = str.replaceAll("\\b"+toBeReplaced+"\\b", replacementValue);
                }
                // Write the fully replaced line to the temp file:
                out.append(str);
                out.newLine();

                // Do not forget to read the next line:
                str = in.readLine();
            }

        } catch (IOException e) {
            System.out.println("There was a problem:" + e);
        } finally{
            try {
                in.close();
                out.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }


        File f = new File("c:/nursery.txt");
        f.delete();

        File f2 = new File("c:/nursery.tmp");
        f2.renameTo(new File("c:/nursery.txt"));
    }


    public static void main(String[] args) {
        Codage c = new Codage();
        c.doRelpacementInFile();
    }

}

Hope this snippets would be helpful,

Good Luck.

Sign up to request clarification or add additional context in comments.

3 Comments

Good answer, only suggestion i'd give is that when the program is done you clear the hashmap. Also don't do direct c:\ code access. Things like windows 7 will simply prohibit it, you need administrative priveleges and still then its very difficult to write directly to windows root.
@Michael Dibbets: thanks for good hints about clearing the hashmap and the path for file. It was just an example of what's in my mind about using a temp file, and using hashmap instead of tokenizing and using if-else structure. If I really want to write such a code I would pass the file paths and the hashmap to this method.
I'd assume so much. I just wanted to point out the caveats what could trip up your code in the long haul if blindly copied :-)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.