java读取文件
什么是流?
流是一组有顺序的,有起点和终点的字节集合,是对数据传输的总称或抽象。即数据在两设备间的传输称为流。流的本质是数据传输,根据数据传输特性将流抽象为各种类,方便更直观的进行数据操作。
流的分类
1、按数据流的方向不同,可分为输出流、输入流;
2、按处理数据单位不同,可分为字节流、字符流;
3、按功能不同,可分为节点流、处理流;
本文主要通过通过字节数组读取。
1.在windows本地
(1)写
package weifenbu;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
public class benxie {
public static void main(String[] args) throws Exception {
// TODO Auto-generated method stub
File file=new File("d:/wxy1.txt"); //指定路径
file.createNewFile();
FileOutputStream fos=new FileOutputStream(file);
byte b[]="这是一个测试 this is a test".getBytes();
fos.write(b);
fos.close();
}
}
(2)读
package weifenbu;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStreamReader;
public class weifenbudu {
public static void main(String[] args) throws Exception {
// TODO Auto-generated method stub
File file=new File("d:/wxy1.txt");
FileInputStream fin=new FileInputStream(file);
InputStreamReader in=new InputStreamReader(fin,"utf-8"); //获取输入流
BufferedReader br = new BufferedReader(in);
char[] buf=new char[fin.available()];
br.read(buf); //br的效率更高,带缓冲
in.close();
fin.close();
System.out.println(buf);
}
}
中文在读取的时候可能会产生乱码 ,需要设置正确的编码比如:“utf-8”。
为什么中文会产生乱码,而英文和数字不会:
原因是虽然编码的方式有很多种,但是英文和数字的编码基本都是一样的。而中文编码方案差别比较大。
比如存入的时候使用的是编码方案x: 四位代表一个文字 0010 1100
而读的时候采用的编码方案y: 3位代表一个文字 001 011 00 所以才会产生乱码。
2.分布式模式下
前提准备:eclipse已经连接hadoop集群
1.写
package hdduxie;
import java.io.IOException;
import java.net.URI;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FSDataOutputStream;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
public class hdxie {
public static void main(String[] args) throws Exception {
// TODO Auto-generated method stub
Configuration conf = new Configuration();
FileSystem fs=FileSystem.get(new URI("hdfs://master:9000"),conf,"user");//表明是完全分布式环境下
byte[] b="hello java,hello hadoop".getBytes();//设置要写的内容
FSDataOutputStream out=fs.create(new Path("/wxy.txt"));//获取输出流并创建一个文件对象
out.write(b);//执行写操作
out.close();//关闭流
fs.close();//关闭流
}
}
2.读
import java.net.URISyntaxException;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FSDataInputStream;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
public class hddu {
public static void main(String[] args) throws Exception {
// TODO Auto-generated method stub
Configuration conf = new Configuration();
FileSystem fs=FileSystem.get(new URI("hdfs://master:9000"),conf);
Path path=new Path("/wxy.txt"); //获取一个文件对象
FSDataInputStream fin=fs.open(path);
byte[] b=new byte[fin.available()];
fin.read(b);
fin.close();
fs.close();
System.out.println("内容:"+new String(b,"utf-8"));
}
}