- hadoop文件的上传函数IOUtils.copyBytes(fis,fos,configuration);
- java的文件输入输出流的
注意:导入的包的问题,如果导入的包不对会报错,基本上是hadoop包的导入,但是注意这个包:
import java.net.URI;//导入的是net网络的这个包,而不是其他的包
实现代码:
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FSDataInputStream;
import org.apache.hadoop.fs.FSDataOutputStream;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.IOUtils;
import org.junit.Test;
import java.io.*;
import java.net.URI;//导入的是net网络的这个包,而不是其他的包
import java.net.URISyntaxException;
public class TestHadoopIO {
@Test
//hadoop的io流的测试
public void JavaIOtest() throws Exception{
// a.exe复制出了b.exe
// 定义输出流
InputStream is=new FileInputStream("a.exe");
// 定义输入流
File file=new File("b.exe");
if(!file.exists()){
file.createNewFile();//如果文件没有存在就创建一个新的文件
}
// 定义输出流写到指定的文件
OutputStream os=new FileOutputStream(file);
// 定义缓冲区,使用读写更加的便利
byte[] buffer=new byte[1024];
int len=0;
while((len=is.read(buffer))!=-1){
//把is写入的数据写到磁盘中
os.write(buffer,0,len);
}
//同步到磁盘
os.flush();
// 关闭相关的操作
os.close();
is.close();
}
@Test
//获取文件系统
public void hadoopIOtest() throws IOException, URISyntaxException, InterruptedException {
Configuration cfg=new Configuration();
FileSystem fs=FileSystem.get(new URI("hadoop100:9000"),cfg,"dev1");
//将win10的文件上传到hdfs
// 定义输入流
InputStream is=fs.open(new Path("/abc.txt"));
}
// 上传文件到hdfs copyBytes(fis,fos,configuration);
@Test
public void putFileToHDFS() throws IOException, InterruptedException, URISyntaxException {
// 1 获取文件系统
Configuration configuration = new Configuration();
FileSystem fs = FileSystem.get(new URI("hdfs://hadoop100:9000"), configuration, "dev1");
// 2 创建输入流
FileInputStream fis = new FileInputStream(new File("e:/banhua.txt"));
// 3 获取输出流
FSDataOutputStream fos = fs.create(new Path("/banhua.txt"));
IOUtils.copyBytes(fis,fos,configuration);
// 5 关闭资源 先打开的后关闭
IOUtils.closeStream(fos);
IOUtils.closeStream(fis);
fs.close();
}
}