-1

In below code, I'm trying to create a text file and there I want to add some list of values. My approach is to 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("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

   BBBB2222
   CCCC2222

Expected output

  BBBB
  CCCC
  AAAA1111
  BBBB2222
  CCCC2222
Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197

1 Answers1

0

You can simply use one class and 2 methods as below: Simply add content in the File using for-each loop and FileWriter class.

 public static void main(String[] args) throws Exception  {
         //sftp.sftpGetConnect();
    List<String> list =  new ArrayList<>();
    list.add("BBBB");
    list.add("CCCC");
    writeIntoText(list);
    List<String> list1 =  new ArrayList<>();
    list1.add("AAAA1111");
    list1.add("BBBB2222");
    list1.add("CCCC2222");
    writeIntoText(list1);
}
public static void writeIntoText(List<String> result) throws Exception
{
 
    FileWriter fstream = new FileWriter("log.txt",true);
    BufferedWriter out = new BufferedWriter(fstream);
    for (String s : result) {
        out.write(s+"\n");
    }
out.close();
}
garima garg
  • 308
  • 1
  • 8