有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

Concat在java中的文件中无法正常工作

我必须做一个没有swing库的项目。我必须浏览文件,并尝试执行以下操作:

fichero = new File(fichero.getAbsolutePath().concat("\\" + str));

其中str是要访问的新目录

希望有人能帮助我。 多谢各位


共 (2) 个答案

  1. # 1 楼答案

    这个

    fichero = new File(fichero.getAbsolutePath() + "\\" + str);
    

    fichero = new File(fichero.getAbsolutePath() + "/" + str);
    

    fichero = new File(fichero.getAbsolutePath().concat("/").concat(str);
    

    应该行得通

  2. # 2 楼答案

    您可以使用\\/。我建议您使用后者,因为它与平台无关

    此外,请使用构造函数:

    File(String parent, String child)  
    

    文件说:

    Creates a new File instance from a parent pathname string and a child pathname string. If parent is null then the new File instance is created as if by invoking the single-argument File constructor on the given child pathname string.

    Otherwise the parent pathname string is taken to denote a directory, and the child pathname string is taken to denote either a directory or a file. If the child pathname string is absolute then it is converted into a relative pathname in a system-dependent way. If parent is the empty string then the new File instance is created by converting child into an abstract pathname and resolving the result against a system-dependent default directory. Otherwise each pathname string is converted into an abstract pathname and the child abstract pathname is resolved against the parent.

    因此,您的代码应该如下所示:

    fichero = new File(fichero.getAbsolutePath(),str);  
    

    NB:您还可以使用接受FileString作为参数的File构造函数,从而消除对getAbsolutePath()的调用