java字节读取文件
Ⅰ java读取文件问题该选字节流还是字符流
如果文本文件通常使用字符流,而像视频、图片、音频等文件都是二进制数据,使用字节流,当然文本文件也是可以通过字节流来读取和写入的,字节流更通用,字符流只不过是对字节流进行了封装,查表操作。希望可以帮到你的疑问
Ⅱ java怎么利用字节流读取文件
File a=new File("文件名"); //创建文件
FileInputStream b=new FileInputStream(a); //创建字节输入流
b.read(); //读
Ⅲ java中如何读取文件中内容,并打印日历
public class ReadFromFile {
/**
* 以字节为单位读取文件,常用于读二进制文件,如图片、声音、影像等文件。
*/
public static void readFileByBytes(String fileName) {
File file = new File(fileName);
InputStream in = null;
try {
System.out.println("以字节为单位读取文件内容,一次读一个字节:");
// 一次读一个字节
in = new FileInputStream(file);
int tempbyte;
while ((tempbyte = in.read()) != -1) {
System.out.write(tempbyte);
}
in.close();
} catch (IOException e) {
e.printStackTrace();
return;
}
try {
System.out.println("以字节为单位读取文件内容,一次读多个字节:");
// 一次读多个字节
byte[] tempbytes = new byte[100];
int byteread = 0;
in = new FileInputStream(fileName);
ReadFromFile.showAvailableBytes(in);
// 读入多个字节到字节数组中,byteread为一次读入的字节数
while ((byteread = in.read(tempbytes)) != -1) {
System.out.write(tempbytes, 0, byteread);
}
} catch (Exception e1) {
e1.printStackTrace();
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e1) {
}
}
}
}
/**
* 以字符为单位读取文件,常用于读文本,数字等类型的文件
*/
public static void readFileByChars(String fileName) {
File file = new File(fileName);
Reader reader = null;
try {
System.out.println("以字符为单位读取文件内容,一次读一个字节:");
// 一次读一个字符
reader = new InputStreamReader(new FileInputStream(file));
int tempchar;
while ((tempchar = reader.read()) != -1) {
// 对于windows下,\r\n这两个字符在一起时,表示一个换行。
// 但如果这两个字符分开显示时,会换两次行。
// 因此,屏蔽掉\r,或者屏蔽\n。否则,将会多出很多空行。
if (((char) tempchar) != '\r') {
System.out.print((char) tempchar);
}
}
reader.close();
} catch (Exception e) {
e.printStackTrace();
}
try {
System.out.println("以字符为单位读取文件内容,一次读多个字节:");
// 一次读多个字符
char[] tempchars = new char[30];
int charread = 0;
reader = new InputStreamReader(new FileInputStream(fileName));
// 读入多个字符到字符数组中,charread为一次读取字符数
while ((charread = reader.read(tempchars)) != -1) {
// 同样屏蔽掉\r不显示
if ((charread == tempchars.length)
&& (tempchars[tempchars.length - 1] != '\r')) {
System.out.print(tempchars);
} else {
for (int i = 0; i < charread; i++) {
if (tempchars[i] == '\r') {
continue;
} else {
System.out.print(tempchars[i]);
}
}
}
}
} catch (Exception e1) {
e1.printStackTrace();
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e1) {
}
}
}
}
/**
* 以行为单位读取文件,常用于读面向行的格式化文件
*/
public static void readFileByLines(String fileName) {
File file = new File(fileName);
BufferedReader reader = null;
try {
System.out.println("以行为单位读取文件内容,一次读一整行:");
reader = new BufferedReader(new FileReader(file));
String tempString = null;
int line = 1;
// 一次读入一行,直到读入null为文件结束
while ((tempString = reader.readLine()) != null) {
// 显示行号
System.out.println("line " + line + ": " + tempString);
line++;
}
reader.close();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e1) {
}
}
}
}
/**
* 随机读取文件内容
*/
public static void readFileByRandomAccess(String fileName) {
RandomAccessFile randomFile = null;
try {
System.out.println("随机读取一段文件内容:");
// 打开一个随机访问文件流,按只读方式
randomFile = new RandomAccessFile(fileName, "r");
// 文件长度,字节数
long fileLength = randomFile.length();
// 读文件的起始位置
int beginIndex = (fileLength > 4) ? 4 : 0;
// 将读文件的开始位置移到beginIndex位置。
randomFile.seek(beginIndex);
byte[] bytes = new byte[10];
int byteread = 0;
// 一次读10个字节,如果文件内容不足10个字节,则读剩下的字节。
// 将一次读取的字节数赋给byteread
while ((byteread = randomFile.read(bytes)) != -1) {
System.out.write(bytes, 0, byteread);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (randomFile != null) {
try {
randomFile.close();
} catch (IOException e1) {
}
}
}
}
/**
* 显示输入流中还剩的字节数
*/
private static void showAvailableBytes(InputStream in) {
try {
System.out.println("当前字节输入流中的字节数为:" + in.available());
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
String fileName = "C:/temp/newTemp.txt";
ReadFromFile.readFileByBytes(fileName);
ReadFromFile.readFileByChars(fileName);
ReadFromFile.readFileByLines(fileName);
ReadFromFile.readFileByRandomAccess(fileName);
}
}
Ⅳ JAVA中读取文件(二进制,字符)内容的几种方
JAVA中读取文件内容的方法有很多,比如按字节读取文件内容,按字符读取文件内容,按行读取文件内容,随机读取文件内容等方法,本文就以上方法的具体实现给出代码,需要的可以直接复制使用
public class ReadFromFile {
/**
* 以字节为单位读取文件,常用于读二进制文件,如图片、声音、影像等文件。
*/
public static void readFileByBytes(String fileName) {
File file = new File(fileName);
InputStream in = null;
try {
System.out.println("以字节为单位读取文件内容,一次读一个字节:");
// 一次读一个字节
in = new FileInputStream(file);
int tempbyte;
while ((tempbyte = in.read()) != -1) {
System.out.write(tempbyte);
}
in.close();
} catch (IOException e) {
e.printStackTrace();
return;
}
try {
System.out.println("以字节为单位读取文件内容,一次读多个字节:");
// 一次读多个字节
byte[] tempbytes = new byte[100];
int byteread = 0;
in = new FileInputStream(fileName);
ReadFromFile.showAvailableBytes(in);
// 读入多个字节到字节数组中,byteread为一次读入的字节数
while ((byteread = in.read(tempbytes)) != -1) {
System.out.write(tempbytes, 0, byteread);
}
} catch (Exception e1) {
e1.printStackTrace();
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e1) {
}
}
}
}
/**
* 以字符为单位读取文件,常用于读文本,数字等类型的文件
*/
public static void readFileByChars(String fileName) {
File file = new File(fileName);
Reader reader = null;
try {
System.out.println("以字符为单位读取文件内容,一次读一个字节:");
// 一次读一个字符
reader = new InputStreamReader(new FileInputStream(file));
int tempchar;
while ((tempchar = reader.read()) != -1) {
// 对于windows下,\r\n这两个字符在一起时,表示一个换行。
// 但如果这两个字符分开显示时,会换两次行。
// 因此,屏蔽掉\r,或者屏蔽\n。否则,将会多出很多空行。
if (((char) tempchar) != '\r') {
System.out.print((char) tempchar);
}
}
reader.close();
} catch (Exception e) {
e.printStackTrace();
}
try {
System.out.println("以字符为单位读取文件内容,一次读多个字节:");
// 一次读多个字符
char[] tempchars = new char[30];
int charread = 0;
reader = new InputStreamReader(new FileInputStream(fileName));
// 读入多个字符到字符数组中,charread为一次读取字符数
while ((charread = reader.read(tempchars)) != -1) {
// 同样屏蔽掉\r不显示
if ((charread == tempchars.length)
&& (tempchars[tempchars.length - 1] != '\r')) {
System.out.print(tempchars);
} else {
for (int i = 0; i < charread; i++) {
if (tempchars[i] == '\r') {
continue;
} else {
System.out.print(tempchars[i]);
}
}
}
}
} catch (Exception e1) {
e1.printStackTrace();
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e1) {
}
}
}
}
/**
* 以行为单位读取文件,常用于读面向行的格式化文件
*/
public static void readFileByLines(String fileName) {
File file = new File(fileName);
BufferedReader reader = null;
try {
System.out.println("以行为单位读取文件内容,一次读一整行:");
reader = new BufferedReader(new FileReader(file));
String tempString = null;
int line = 1;
// 一次读入一行,直到读入null为文件结束
while ((tempString = reader.readLine()) != null) {
// 显示行号
System.out.println("line " + line + ": " + tempString);
line++;
}
reader.close();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e1) {
}
}
}
}
/**
* 随机读取文件内容
*/
public static void readFileByRandomAccess(String fileName) {
RandomAccessFile randomFile = null;
try {
System.out.println("随机读取一段文件内容:");
// 打开一个随机访问文件流,按只读方式
randomFile = new RandomAccessFile(fileName, "r");
// 文件长度,字节数
long fileLength = randomFile.length();
// 读文件的起始位置
int beginIndex = (fileLength > 4) ? 4 : 0;
// 将读文件的开始位置移到beginIndex位置。
randomFile.seek(beginIndex);
byte[] bytes = new byte[10];
int byteread = 0;
// 一次读10个字节,如果文件内容不足10个字节,则读剩下的字节。
// 将一次读取的字节数赋给byteread
while ((byteread = randomFile.read(bytes)) != -1) {
System.out.write(bytes, 0, byteread);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (randomFile != null) {
try {
randomFile.close();
} catch (IOException e1) {
}
}
}
}
/**
* 显示输入流中还剩的字节数
*/
private static void showAvailableBytes(InputStream in) {
try {
System.out.println("当前字节输入流中的字节数为:" + in.available());
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
String fileName = "C:/temp/newTemp.txt";
ReadFromFile.readFileByBytes(fileName);
ReadFromFile.readFileByChars(fileName);
ReadFromFile.readFileByLines(fileName);
ReadFromFile.readFileByRandomAccess(fileName);
}
}
Ⅳ java怎么读取和写入字节文件开发环境 MyEclipse 8.6
InputStream
三个基本的读方法
abstract
int
read()
:
读取一个字节数据,并返回读到的数据,如果返回-1,表示读到了输入流的末尾。
int
read(byte[]
b)
:
将数据读入一个字节数组,同时返回实际读取的字节数。如果返回-1,表示读到了输入流的末尾。
int
read(byte[]
b,
int
off,
int
len)
:将数据读入一个字节数组,同时返回实际读取的字节数。如果返回-1,表示读到了输入流的末尾。off指定在数组b中存放数据的起始偏移位置;len指定读取的最大字节数。
OutputStream
三个基本的写方法
abstract
void
write(int
b)
:往输出流中写入一个字节。
void
write(byte[]
b)
:往输出流中写入数组b中的所有字节。
void
write(byte[]
b,
int
off,
int
len)
:往输出流中写入数组b中从偏移量off开始的len个字节的数据。
其它方法
void
flush()
:刷新输出流,强制缓冲区中的输出字节被写出。
void
close()
:关闭输出流,释放和这个流相关的系统资源。
Ⅵ Java 如何读取txt文件的内容
java读取txt文件内容。可以作如下理解:
首先获得一个文件句柄。File file = new File(); file即为文件句柄。两人之间连通电话网络了。接下来可以开始打电话了。
通过这条线路读取甲方的信息:new FileInputStream(file) 目前这个信息已经读进来内存当中了。接下来需要解读成乙方可以理解的东西
既然你使用了FileInputStream()。那么对应的需要使用InputStreamReader()这个方法进行解读刚才装进来内存当中的数据
解读完成后要输出呀。那当然要转换成IO可以识别的数据呀。那就需要调用字节码读取的方法BufferedReader()。同时使用bufferedReader()的readline()方法读取txt文件中的每一行数据哈。
packagecom.campu;
importjava.io.BufferedInputStream;
importjava.io.BufferedReader;
importjava.io.File;
importjava.io.FileInputStream;
importjava.io.InputStreamReader;
importjava.io.Reader;
/**
*@authorJava团长
*H20121012.java
*2017-10-29上午11:22:21
*/
publicclassH20121012{
/**
*功能:Java读取txt文件的内容
*步骤:1:先获得文件句柄
*2:获得文件句柄当做是输入一个字节码流,需要对这个输入流进行读取
*3:读取到输入流后,需要读取生成字节流
*4:一行一行的输出。readline()。
*备注:需要考虑的是异常情况
*@paramfilePath
*/
publicstaticvoidreadTxtFile(StringfilePath){
try{
Stringencoding="GBK";
Filefile=newFile(filePath);
if(file.isFile()&&file.exists()){//判断文件是否存在
InputStreamReaderread=newInputStreamReader(
newFileInputStream(file),encoding);//考虑到编码格式
BufferedReaderbufferedReader=newBufferedReader(read);
StringlineTxt=null;
while((lineTxt=bufferedReader.readLine())!=null){
System.out.println(lineTxt);
}
read.close();
}else{
System.out.println("找不到指定的文件");
}
}catch(Exceptione){
System.out.println("读取文件内容出错");
e.printStackTrace();
}
}
publicstaticvoidmain(Stringargv[]){
StringfilePath="L:\Apache\htdocs\res\20121012.txt";
//"res/";
readTxtFile(filePath);
}}
我有一个微信公众号,经常会分享一些Java技术相关的干货文章,还有一些学习资源。
如果你需要的话,可以用微信搜索“Java团长”或者“javatuanzhang”关注。
Ⅶ 用java如何读取一个文件的指定字节位置的数据
可以使用RandomAccessFile类。例如要从100字节开始输出工作目录下的data.txt文件的类容。
package konw.test1;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
public class Test1
{
public static void main(String[] args)
{
long pos = 100;
try
{
String str = "";
RandomAccessFile randomAccessFile = new RandomAccessFile("data.txt", "rw");
randomAccessFile.seek(pos);//将文件流的位置移动到pos字节处
while( (str = randomAccessFile.readLine()) != null)
{
System.out.println(str);
}
randomAccessFile.close();
} catch (FileNotFoundException e)
{
e.printStackTrace();
} catch (IOException e)
{
e.printStackTrace();
}
}
}
Ⅷ java中怎样按字节读取文件并复制到另一个文件夹
这里以字节流FileInputStream,FileOutputStream为例。代码例子如下:
importjava.io.File;
/**
*把一个文件夹中的文件复制到一个指定的文件夹
*@authoryoung
*
*/
importjava.io.FileInputStream;
importjava.io.FileNotFoundException;
importjava.io.FileOutputStream;
importjava.io.IOException;
publicclassCopyFile{
publicstaticvoidmain(String[]args){
/*指定源exe文件的存放路径*/
Stringstr="f:/jdk-1_5_0_06-windows-i586-p.exe";
/*指定复制后的exe的目标路径*/
Stringstrs="e:/.exe";
/*创建输入和输出流*/
FileInputStreamfis=null;
FileOutputStreamfos=null;
try{
/*将io流和文件关联*/
fis=newFileInputStream(str);
fos=newFileOutputStream(strs);
byte[]buf=newbyte[1024*1024];
intlen;
while((len=fis.read(buf))!=-1){
fos.write(buf,0,len);
}
}catch(FileNotFoundExceptione){
//TODOAuto-generatedcatchblock
e.printStackTrace();
}catch(IOExceptione){
//TODOAuto-generatedcatchblock
e.printStackTrace();
}finally{
try{
fis.close();
fos.close();
}catch(IOExceptione){
//TODOAuto-generatedcatchblock
e.printStackTrace();
}
}
}
}
Ⅸ java的几种IO流读取文件方式
一、超类:
字节流: InputStream(读入流) OutputStream(写出流)
字符流: Reader(字符 读入流) Writer (字符写出流)
二、文件操作流
字节流: FileInputStream ,FileOutputStream
字符流: FileReader, FileWriter(用法与字节流基本相同,不写)
//1.指定要读 的文件目录及名称
File file =new File("文件路径");
//2.创建文件读入流对象
FileInputStream fis =new FileInputStream(file);
//3.定义结束标志,可用字节数组读取
int i =0 ;
while((i = fis.read())!=-1){
//i 就是从文件中读取的字节,读完后返回-1
}
//4.关闭流
fis.close();
//5.处理异常
//1.指定要写到的文件目录及名称
File file =new File("文件路径");
//2.创建文件读入流对象
FileOutputStream fos =new FileOutputStream(file);
//3.定义结束标志
fos.write(要写出的字节或者字节数组);
//4.刷新和关闭流
fos.flush();
fos.close();
//5.处理异常
三、缓冲流:
字节缓冲流: BufferedInputStream,BufferedOutputStream
字符缓冲流:BufferedReader ,BufferedWriter
缓冲流是对流的操作的功能的加强,提高了数据的读写效率。既然缓冲流是对流的功能和读写效率的加强和提高,所以在创建缓冲流的对象时应该要传入要加强的流对象。
//1.指定要读 的文件目录及名称
File file =new File("文件路径");
//2.创建文件读入流对象
FileInputStream fis =new FileInputStream(file);
//3.创建缓冲流对象加强fis功能
BufferedInputStream bis =new BufferedInputStream(fis);
//4.定义结束标志,可用字节数组读取
int i =0 ;
while((i = bis.read())!=-1){
//i 就是从文件中读取的字节,读完后返回-1
}
//5.关闭流
bis.close();
//6.处理异常
//1.指定要写到的文件目录及名称
File file =new File("文件路径");
//2.创建文件读入流对象
FileOutputStream fos =new FileOutputStream(file);
//3.创建缓冲流对象加强fos功能
BufferedOutputStream bos=new BufferedOutputStream(fos);
//4.向流中写入数据
bos.write(要写出的字节或者字节数组);
//5.刷新和关闭流
bos.flush();
bos.close();
//6.处理异常
四、对象流
ObjectInputStream ,ObjectOutputStream
不同于以上两种类型的流这里只能用字节对对象进行操作原因可以看上篇的编码表比照原理
ObjectOutputStream对象的序列化:
将java程序中的对象写到本地磁盘里用ObjectOutputStream
eg:将Person类的对象序列化到磁盘
创建Person类
注1:此类要实现Serializable接口,此接口为标志性接口
注2:此类要有无参的构造函数
注3:一旦序列化此类不能再修改
class Person implements Serializable{
public Person(){}
}
2.创建对象流对象
注:要增强功能可以将传入文件缓冲流
ObjectOutputStream oos =new ObjectOutputStream(
new FileOutputStream(new File("文件路径")));
3.写入对象 ,一般会将对象用集合存储起来然后直接将集合写入文件
List<Person> list =new ArrayList<>();
list.add(new Person());
...(可以添加多个)
oos.writeObject(list);
4.关闭流,处理异常
oos.flush();
oos.close();
五、转换流:
这类流是用于将字符转换为字节输入输出,用于操作字符文件,属于字符流的子类,所以后缀为reader,writer;前缀inputstream,outputstream;
注 :要传入字节流作为参赛
InputStreamReader: 字符转换输出流
OutputStreamWriter:字符转换输入流
//1.获取键盘输入的字节流对象
inInputStream in =Stream.in;
/*2.用转换流将字节流对象转换为字符流对象,方便调用字符缓冲流的readeLine()方法*/
InputStreamReader isr =new InputStreamReader(in);
/*5.创建字符转换输出流对象osw,方便把输入的字符流转换为字节输出到本地文件。*/
OutputStreamWriter osw =new OutputStreamWriter(new
FileOutputStream(new File("文件名")));
/*3.现在isr是字符流,可以作为参数传入字符缓冲流中*/
BufferedReader br =new BufferedReader(isr);
/*4.可以调用字符缓冲流br的readLine()方法度一行输入文本*/
String line =null;
while((line =br.readLine()){
osw.write(line);//osw是字符流对象,可以直接操作字符串
}
注:InputStreamReader isr =new InputStreamReader(new "各种类型的字节输入流都行即是:后缀为InputStream就行");
OutputStreamWriter osw =new OutputStreamWriter(new
"后缀为OutputStream就行");
六、区别记忆
1.对象流是可以读写几乎所有类型的只要是对象就行,而字节字符流,只能读写单个字节字符或者字节字符数组,以上没有读写字节字符数组的;注意对象流只有字节流!
2.字符和字节循环读入的结束条件int i=0; (i =fis.read())!=-1
用字符数组复制文件(fr 读入流 ,fw写出流),字节流也是相同的用法
int i = 0; char[] c = new char[1024];
while((i = fr.reade()) !=-1)){
fw.write(c,0,i);
}
123456
3.对象流里面套缓冲流的情景:
new ObjectInputStream(new BufferedInputStream(new FileInputStream(new File(“文件路径”))));
4.记忆流及其功能的方法:
前缀表示功能,后缀表示流的类型;
比如说FileInputStream 前缀:File,表示操作的磁盘,后缀:intputstream,表示是字节输入流。
同理 FileReader:表示操作文件的字符流
ObjectInputStream :操作对象的字节输入流
5.拓展:获取键盘输入的字符的缓冲流的写法:
new BufferedReader(new InputStreamReader(System.in)));
将字节以字符形式输出到控制台的字符缓冲流的写法:
new BufferedWriter( new OutputStreamWriter(System.out))
Ⅹ java分别以字节流和字符流的两种方式读取文件内容
importjava.io.BufferedReader;
importjava.io.File;
importjava.io.FileInputStream;
importjava.io.IOException;
importjava.io.InputStreamReader;
importjava.io.PrintWriter;
publicclassTest10{
/**
*复制当前的源程序到项目的根目录
*@throwsIOException
*/
publicstaticvoidmain(String[]args)throwsIOException{
/*
*1:读取原文件
*2:项目标文件中写
*3:使用缓冲流按行读写
*/
FileInputStreamfis=newFileInputStream("src"+File.separator+"day01"+File.separator+"Test1.java");
//转化为字符输出流
InputStreamReaderisr=newInputStreamReader(fis);
//按行为单位读取字符串
BufferedReaderbr=newBufferedReader(isr);
//
PrintWriterpw=newPrintWriter("Test1.java");
Stringline=null;
while((line=br.readLine())!=null){
pw.println(line);
}
pw.close();
br.close();
}
}