Writing String to Text File

后端 未结 6 1676
太阳男子
太阳男子 2021-01-29 01:21

I am saving a log to a .txt file on the sdcard but once there is two lines saved, it overwrites it and starts over?

Here is my code:

public static Strin         


        
6条回答
  •  情歌与酒
    2021-01-29 01:48

    I am able to append the file using your code, can you please check this code

        import java.io.BufferedWriter;
        import java.io.FileWriter;
        import java.io.IOException;
        import java.io.PrintWriter;
        import java.util.Date;
        import java.text.SimpleDateFormat;
        import java.util.Locale;
    
        public class Test {
            public static String getTimestamp() {
                try {
    
                    SimpleDateFormat dateFormat = new SimpleDateFormat(
                            "MMMdd HH:mm:ss", Locale.getDefault());
                    String currentTimeStamp = dateFormat.format(new Date());
    
                    return currentTimeStamp;
                } catch (Exception e) {
                    e.printStackTrace();
    
                    return null;
                }
            }
    
            public static void writeToLog(String string) {
                String text = getTimestamp() + " " + string;
                // ONLY SAVES TWO LINES
                try {
                    PrintWriter out = new PrintWriter(new BufferedWriter(
                            new FileWriter("c:/log.txt", true)));
                    out.println(text);
                    out.close();
                } catch (IOException e) {
                }
            }
    
            public static void main(String[] args) throws Exception {
                writeToLog("Connected to WIFI");
    
            }
        }
    

    OUPUT :
    Sep05 16:13:28 Connected to WIFI
    Sep05 16:13:48 Connected to WIFI
    Sep05 16:13:49 Connected to WIFI
    Sep05 16:13:50 Connected to WIFI
    Sep05 16:15:54 Connected to WIFI
    Sep05 16:15:55 Connected to WIFI
    Sep05 16:15:55 Connected to WIFI
    Sep05 16:15:56 Connected to WIFI
    Sep05 16:15:57 Connected to WIFI
    Sep05 16:15:58 Connected to WIFI
    Sep05 16:15:59 Connected to WIFI
    Sep05 16:16:01 Connected to WIFI

提交回复
热议问题