【问题标题】:adding File to a String?将文件添加到字符串?
【发布时间】:2026-01-06 19:05:01
【问题描述】:

我刚刚发现了这行奇怪的代码,它可以编译:

String a = (new File("")) + "f";
System.out.println(a);

输出:

f

我在 Windows 10 Pro 上的 Eclipse Neon.2 上使用 jre 1.8_111。

它只用一个空的 String 初始化程序编译,但我认为它不应该,因为 + 运算符没有为 File 重载。还是这样?

我检查了new File("") 不是null,但它的filePathstatus 是。

任何想法为什么它编译?

【问题讨论】:

标签: java string file


【解决方案1】:

您的代码可读性差

File file = new File("c");
String a = file.toString() + "f";

【讨论】:

  • @GregT:这与您要问的字符串连接运算符的相关性如何?