简体   繁体   English

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

[英]Concat doesn't work properly in files in java

I have to do a project without the swing library.I have to browse over the files and was trying to do something like this: 我必须做一个没有swing库的项目。我必须浏览文件并试图做这样的事情:

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

where str is the new Directory that you want to access 其中str是您要访问的新目录

Hope someone could help me. 希望有人可以帮助我。 Thank you 谢谢

This 这个

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

or 要么

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

or 要么

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

should work fine. 应该工作正常。

You may use \\\\ or you may use a / . 您可以使用\\\\ ,也可以使用/ I suggest you use the latter as it is platform independent. 我建议您使用后者,因为它与平台无关。

Also, use the constructor: 另外,使用构造函数:

File(String parent, String child)  

The docs say: 文档说:

Creates a new File instance from a parent pathname string and a child pathname string. 根据父路径名字符串和子路径名字符串创建一个新的File实例。 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. 如果parent为null,则将通过在给定的子路径名字符串上调用单参数File构造函数来创建新的File实例。

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. 如果parent是空字符串,则通过将child转换为抽象路径名并针对与系统相关的默认目录解析结果来创建新的File实例。 Otherwise each pathname string is converted into an abstract pathname and the child abstract pathname is resolved against the parent. 否则,每个路径名字符串都将转换为抽象路径名,而子抽象路径名将针对父路径解析。

So, your code should look like: 因此,您的代码应如下所示:

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

NB: You may also use the File constructor that accepts a File and String as an argument, thus eliminating the call to getAbsolutePath() 注意:您也可以使用接受FileString作为参数的File构造函数,从而消除对getAbsolutePath()的调用

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM