我开发了一个代码,可以从 FTP 读取非常大的文件并使用 Java 将其写入本地机器。执行它的代码如下。这是 CustomInputFormat
RecordReader
中的 next(Text key, Text value)
的一部分
if(!processed)
{
System.out.println("in processed");
in = fs.open(file);
processed=true;
}
while(bytesRead <= fileSize) {
byte buf[] = new byte[1024];
try {
in.read(buf);
in.skip(1024);
bytesRead+=1024;
long diff = fileSize-bytesRead;
if(diff<1024)
{
break;
}
value.set(buf, 0, 1024); // This is where the value of the record is set and it goes to the mapper .
}
catch(Exception e)
{
e.printStackTrace();
}
}
if(diff<1024)
{
int difference= (int) (fileSize-bytesRead);
byte buf[] = new byte[difference];
in.read(buf);
bytesRead+=difference;
}
System.out.println("closing stream");
in.close();
写入结束后,我看到传输完成,目标文件的大小与源文件的大小相同。但是我无法打开文件,编辑器给出了错误
gedit has not been able to detect the character coding.
Please check that you are not trying to open a binary file.
Select a character coding from the menu and try again.
这个问题:Java upload jpg using JakartaFtpWrapper - makes the file unreadable我相信与我的有关,但我无法理解。
有什么指点吗?
最佳答案
你的复制代码是完整的,而且是 100% 的 A 级废话。在 Java 中复制流的规范方法如下:
int count;
byte[] buffer = new byte[8192]; // or more if you like
while ((count = in.read(buffer)) > 0)
{
out.write(buffer, 0, count);
}
摆脱所有其他绒毛。这只会浪费时间和空间,并且显然会损坏传输中的数据。
关于java - 使用Java从FTP下载文件到本地导致文件不可读-编码问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14117719/