运行后重置文件

时间:2014-01-12 06:54:29

标签: java file filereader filewriter

好的,我正在编写一些会产生密码的东西,并为每个字母分配一个随机值为2到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();
        }
    }

好的,它的工作正常。唯一的问题是我希望它保留上一个文件的内容,并将更多内容写入文件,但每次运行后,文件的先前内容都会被删除。有人可以帮忙吗?

1 个答案:

答案 0 :(得分:0)

FileWriter有一个替代构造函数,它将内容附加到文件中,而不是从头开始写:

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.