【问题标题】:File resetting after running [duplicate]运行后文件重置[重复]
【发布时间】:2014-01-12 06:54:29
【问题描述】:

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

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

【问题讨论】:

    标签: java file filereader filewriter


    【解决方案1】:

    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.
    

    【讨论】:

      猜你喜欢
      • 2013-07-14
      • 2017-02-05
      • 1970-01-01
      • 2021-03-29
      • 1970-01-01
      • 2012-12-05
      • 2016-02-25
      • 2017-06-14
      相关资源
      最近更新 更多