gpt4 book ai didi

Java将所有名称写入csv文件

转载 作者:行者123 更新时间:2023-11-30 08:56:52 27 4
gpt4 key购买 nike

  • csv 文件 (test.csv)
    姓名|性别
    阿里|M
    阿布|M
    艾哈迈德|M
    西蒂|F
    拉朱|M

  • 属性文件 (config.properties)
    传入文件名 = test.csv
    OuputFileNameExtension = txt

  • test1.java

    public class test1 {

    public static Properties prop1 = new Properties();

    public static String nameList;

    public test1() throws FileNotFoundException, IOException{
    InputStream input1 = new FileInputStream("config.properties");
    configProp.load(input1);
    }

    public static void main(String[] args) throws IOException {
    test1 t1 = new test1();
    t1.readFileLength(configProp.getProperty("IncomingFileName"));
    }

    public void readFileLength(String filename){

    File file = new File(filename);

    try(Scanner scanner = new Scanner(file)){

    int j = 1;

    while (scanner.hasNextLine()) {

    String line = scanner.nextLine() + " ";

    if (j != 1) {

    String[] records = line.split("\\|");
    String name = records[0];
    String gender = records[1];

    nameList = name;
    }
    j++;
    }

    if(j != 0){

    writeFile("file."+configProp.getProperty
    ("OutputFileNameExtension"), nameList);
    }

    scanner.close();

    }catch(IOException x){
    }

    public void writeFile(String fileName, String nameList) throws IOException{

    File file = new File(fileName);
    FileWriter fileWriter = new FileWriter(file);

    System.out.println(nameList); //show one name only

    fileWriter.flush();
    fileWriter.close();
    }
  • 从上面的代码中,我想把所有的名字都写到csv文件中。但是,我只能显示 1 个名称。 (即阿里)。我如何显示所有csv 文件中的名称?

最佳答案

创建名称的链表:替换String nameList;LinkedList<String> names = new LinkedList<>();

将每个名称添加到列表中:替换 nameList = name;names.add(records[0]);

然后将名称添加到新文件中:

public void writeFile(String fileName, List<String> names) throws IOException{

File file = new File(fileName);
FileWriter fileWriter = new FileWriter(file);
for(String name: names){
filewriter.write(name);//writes the current name to the file. you may need to add a /n or a "," to the name to get approprite line seperations and comas
}

fileWriter.flush();
fileWriter.close();
}

关于Java将所有名称写入csv文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28403151/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com