首页 > 解决方案 > java不能连接到字符串的结尾

问题描述

我正在尝试将“.png”连接到字符串变量“text”的末尾。然而,我尝试的每种方法最终都会用“.png”替换整个字符串。

        Scanner sc = new Scanner(new File("C:/Users/censored/file.csv"));
        //file has "test,test1,test2,test3" from an excel file

        sc.useDelimiter(",");
        sc.useDelimiter("\n");

        while (sc.hasNext()) {
            String text = sc.next();

            String pathname = "C:/Users/censored/" + text;
            System.out.println(pathname); //prints "C:/Users/censored/test"
            pathname += ".png";
            System.out.println(pathname); //prints ".png" only
        }

我觉得它必须与scanner/sc.next()有关,因为如果我将文本定义为字符串文字,我可以获得正确的结果。我能做些什么来解决这个问题?

标签: javastringconcat

解决方案


您使用该useDelimiter()方法的方式,仅使用“\n”

尝试这个:

sc.useDelimiter(",|\\n");

推荐阅读