使用Java复制文件会跳过一行中有两个空格的文件名
这有点令人困惑。以下批处理代码段导致复制这两个文件:使用Java复制文件会跳过一行中有两个空格的文件名,java,exec,whitespace,Java,Exec,Whitespace,这有点令人困惑。以下批处理代码段导致复制这两个文件: xcopy "C:\Source\Spaces1 [ ].txt" "C:\Target\" /Y xcopy "C:\Source\Spaces2 [ ].txt" "C:\Target\" /Y public static void main(final String args[]) throws IOException { final File source1 = new File("C:\\Source", "Spaces
xcopy "C:\Source\Spaces1 [ ].txt" "C:\Target\" /Y
xcopy "C:\Source\Spaces2 [ ].txt" "C:\Target\" /Y
public static void main(final String args[]) throws IOException
{
final File source1 = new File("C:\\Source", "Spaces1 [ ].txt");
final File target1 = new File("C:\\Target", "Spaces1 [ ].txt");
fileCopy(source1, target1);
final File source2 = new File("C:\\Source", "Spaces2 [ ].txt");
final File target2 = new File("C:\\Target", "Spaces2 [ ].txt");
fileCopy(source2, target2);
}
public static void fileCopy(final File source, final File target) throws IOException
{
try (InputStream in = new BufferedInputStream(new FileInputStream(source));
OutputStream out = new BufferedOutputStream(new FileOutputStream(target));)
{
final byte[] buf = new byte[4096];
int len;
while (0 < (len = in.read(buf)))
{
out.write(buf, 0, len);
}
out.flush();
}
}
下面使用streams的Java代码段也会复制这两个文件:
xcopy "C:\Source\Spaces1 [ ].txt" "C:\Target\" /Y
xcopy "C:\Source\Spaces2 [ ].txt" "C:\Target\" /Y
public static void main(final String args[]) throws IOException
{
final File source1 = new File("C:\\Source", "Spaces1 [ ].txt");
final File target1 = new File("C:\\Target", "Spaces1 [ ].txt");
fileCopy(source1, target1);
final File source2 = new File("C:\\Source", "Spaces2 [ ].txt");
final File target2 = new File("C:\\Target", "Spaces2 [ ].txt");
fileCopy(source2, target2);
}
public static void fileCopy(final File source, final File target) throws IOException
{
try (InputStream in = new BufferedInputStream(new FileInputStream(source));
OutputStream out = new BufferedOutputStream(new FileOutputStream(target));)
{
final byte[] buf = new byte[4096];
int len;
while (0 < (len = in.read(buf)))
{
out.write(buf, 0, len);
}
out.flush();
}
}
怎么回事?这将被用来从谁知道是什么来源的地方复制文件,人们可以在那里键入他们喜欢的任何内容。文件名已清理,但谁清理了一行中的两个空格?我错过了什么
目前正在使用Java8,但是Java6和Java7给出了相同的结果。都在Javadoc中
Runtime#exec(String)
委托给Runtime#exec(String,null,null)
exec(String,null,null)
委托给exec(String[]cmdarray,envp,dir)
然后
更准确地说,命令字符串使用由call new StringTokenizer(命令)创建的StringTokenizer分解为标记,而无需进一步修改字符类别。然后,标记器生成的标记按相同顺序放置在新的字符串数组cmdarray中
此时,两个空格丢失,当操作系统重新组装命令字符串时,这两个空格变成一个空格。我尝试用斜杠转义空格(不起作用),我尝试用
%20
(不起作用)替换空格。而且,是的,我已经知道我可以使用Robocopy。你是否尝试过先复制双空间文件,然后复制单空间文件,这会产生相同的结果?是的,我尝试过。好建议,但结果相同。