简体   繁体   English

如何在文本文件中写入多个 ArrayList

[英]How to write multiple ArrayList in a text file

In below code, i'm trying to create a txt file and there i want to add some list of values.在下面的代码中,我正在尝试创建一个 txt 文件,并且我想在其中添加一些值列表。 So here my approach is create a new file if file is not present and add the respective elements into it.所以在这里我的方法是如果文件不存在则创建一个新文件并将相应的元素添加到其中。

Please see below, i'm unable to get my expected output, So can you help me with some idea so it will be very helpful请看下面,我无法得到我预期的 output,所以你能帮我一些想法吗,这样会很有帮助

   public class MyTest {

    public static void main(String[] args) throws Exception  {
        // TODO Auto-generated method stub
        SftpConn sftp = new SftpConn();
        //sftp.sftpGetConnect();
        List<String> list =  new ArrayList<>();
        list.add("AAAA");
        list.add("BBBB");
        list.add("CCCC");
        sftp.writeIntoText(list);
        List<String> list1 =  new ArrayList<>();
        list1.add("AAAA1111");
        list1.add("BBBB2222");
        list1.add("CCCC2222");
        sftp.writeIntoText(list1);
    }
        
    }




 public class SftpConn
      {
    public void writeIntoText(List<String> result) throws Exception
        {
                    connect();
                    List<String> resultdata= result;
                    System.out.println("Result Updated");
                    channelSftp = (ChannelSftp) session.openChannel("sftp");
                    channelSftp.connect();
                    fileOutStream = channelSftp.put("/home/dasrsoum/RM.txt");
                    PrintWriter writer = new PrintWriter(fileOutStream,true);
                    writer.println("------------------");
                    for (String value : resultdata) {
                        writer.println(value+ System.lineSeparator());
                        System.out.println(value);
                    
                    }
                    
            
            writer.close();
   }

Actual output实际 output

 AAAA1111
   BBBB2222
   CCCC2222

Excepted OutPut例外 OutPut

  AAAA
  BBBB
  CCCC
  AAAA1111
  BBBB2222
  CCCC2222

You first file is overwritten by the second call to the function您的第一个文件被第二次调用 function 覆盖

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM