How to write multiple ArrayList in a text file

天大地大妈咪最大 提交于 2021-02-17 07:19:05

问题


In below code , i'm trying to create a txt file and there i want to add some list of values. 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

   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

 AAAA1111
   BBBB2222
   CCCC2222

Excepted OutPut

  AAAA
  BBBB
  CCCC
  AAAA1111
  BBBB2222
  CCCC2222

回答1:


You first file is overwritten by the second call to the function



来源:https://stackoverflow.com/questions/63048653/how-to-write-multiple-arraylist-in-a-text-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!