java - 使用Java从FTP下载文件到本地导致文件不可读-编码问题

标签 java hadoop ftp elastic-map-reduce amazon-emr

我开发了一个代码,可以从 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/

相关文章:

ftp - 如何在 WP7 中实现对 ftp 的支持?

c# - 在单个 ftp 请求中创建一个包含子目录的目录?

java - 如何在 Java 中使用 try-catch 处理不同的异常 http 类型?

hadoop - 输出到文件时,如何将结构编码为 JSON?

hadoop - 在Hadoop 3.1.0中,namenode正常运行,但datanode无效

hadoop - 奥齐 : file and archive tag usage and differences?

c# - 带通配符的 FTP 目录部分列表

java - JNI Linux 段错误

java - 从 MySql 读取大型集合

java - 为什么 JavaCC 无法在我的 Mac 上运行以及如何修复它?