Question

Okay, I'm coding something that will generate a crypt, and assign each letter a string of a random value of anywhere from 2 to 6

    import java.io.*;
    import java.util.*;
    public class filewriters {
        public static void main(String[] args) throws IOException{
            FileWriter a = new FileWriter("crypt.txt");
            char whynot[];
            whynot = new char[97];
            String b[] = new String[97];
            for(int w = 30; w<127; w++){
                char lol =(char) w;
                whynot[w - 30] = lol;
                a.write(lol + " : " );
                String and = "";
                int um = (int) (Math.random() * 5 + 1);
                for(int q = 0; q<um; q++){
                    int well = (int)( Math.random() * 97 + 30);
                    char hello = (char) well;
                    and+= hello;
                }
                b[w - 30] = and;
                a.write(and + "\n");
            }
            toencode(whynot, b);
            a.close();
        }
        private static void toencode(char[] whynot, String[] b) throws IOException{
                Scanner sc = new Scanner(System.in);
                FileWriter themessage = new FileWriter("themessage.txt");
                FileWriter theEncrypted = new FileWriter("encrypted.txt");
                FileWriter toDecode = new FileWriter("DecodeThis.txt");
                String thevar = sc.nextLine();
                char lol[] = thevar.toCharArray();
                for(int w = 0; w < lol.length; w++){
                    char a = lol[w];
                    themessage.write(a + " : ");
                    for(int q = 0; q<whynot.length; q++){
                        if(a == whynot[q]){
                            themessage.write(b[q] + "\n");
                            theEncrypted.write(b[q] + "\n");
                            toDecode.write(b[q]);
                            System.out.println(b[q]);
                        }
                    }
                }
                theEncrypted.close();
                themessage.close();
                toDecode.close();
        }
    }

Okay, it works fine, mostly. The one and only problem is that I want it to keep the contents of the previous file, and write more stuff to the file, but after every run, the previous contents of the file get removed. Can anyone help?

Was it helpful?

Solution

FileWriter has an alternate constructor which will append contents to the file, rather than writing from the beginning:

public FileWriter(String fileName,
          boolean append)
           throws IOException
Constructs a FileWriter object given a file name with a boolean indicating whether or not to append the data written.
Parameters:
fileName - String The system-dependent filename.
append - boolean if true, then data will be written to the end of the file rather than the beginning.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top