英文:
How to write multiple ArrayList in a text file
问题
在下面的代码中,我试图创建一个txt文件,并在其中添加一些值的列表。
因此,我的方法是,如果文件不存在,则创建一个新文件,并将相应的元素添加到其中。
请查看以下内容,我无法获得预期的输出,所以你能帮我提供一些想法,这将非常有帮助。
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();
}
}
实际输出:
AAAA1111
BBBB2222
CCCC2222
预期输出:
AAAA
BBBB
CCCC
AAAA1111
BBBB2222
CCCC2222
英文:
> 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
得分: 3
你的第一个文件会被函数的第二次调用覆盖。
英文:
You first file is overwritten by the second call to the function
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论