最近工作中涉及到一些文件操作的东西,闲下来刚好做个整理。

控制台IO

在控制台使用键盘作为标准输入并使用终端窗口(在windows下,经常是命令提示符或者是PowerShell;在linuxx/OS X下则是terminal)作为标准输出。

java通过java.lang.System类中的三个共有变量支持控制台IO:

System.out

打印一般信息对象,是一个PrintStream对象,该对象默认指的是启动java应用程序的终端窗口。

System.in

输入信息对象,是一个InputStream对象,该对象默认指用户的键盘输入。

System.err

打印错误对象信息,是一个PrintStream对象,该对象默认指的是启动java应用程序的终端窗口。

使用System的静态方法可以重定向这些信息到一个文件流:

System.setOut

System.setIn

System.setErr

java中流的概念及分类:

Java所有的I/O机制都是基于数据流的,这些数据流表示了字符或者字节数据的流动序列。    流是一个很形象的概念,当程序需要读取数据时,就会开启一个通向数据源的流,这个数据源可以是文件,内存,或是网络连接,则这就是“输入流”,(注意:开启数据源,事实上,下文要写入时,也要先开启目的地)。类似的,当程序需要写入数据的时候,就会开启一个通向目的地的流,这就是“输出流”,这时你就可以想像数据好像在这其中“流”动一样。

Java中的流分为两种:

一种是字节流,另一种是字符流    分别由四个抽象类来表示(每种流包括输入和输出各两种,所以一共四个):    InputStream    OutputStream    Reader    Writer

java中的IO库

Java中的字节流是用于处理字节的输入和输出的,包括读写二进制数据等方面的内容。
        InputStream  OutputStream
    而Java中的字符流则用于处理字符的输入和输出,采用的是Unicode编码(这点比C/C++改进了,C/C++中采用的是ASCII码,因此,在其中时,字符是1个字节,而在这里,Unicode编码,一个字符是两个字节,这样,所有的文字都可以表示了),可以实现国际化。
        Reader  Writer
    (1)InputStream
        1)abstract int read()
        2)int read(byte[] b)
        3)int read(byte[] b,int off,int len)
        4)long skip(long n)
        5)int available()
        6)void close()
        7)void mark(int readlimit)
        8)void reset()
        9)boolean markSupported()
    (2)OutputStream
        1)abstract void write(int b)
        2)void write(byte[] b)
        3)void write(byte[] b,int off,int len)
        4)void close()
        5)void flush()
    (3)Reader Writer
        public abstract int read() throws IOException
        public abstract void write() throws IOException

方法代码如下:

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.RandomAccessFile;
import java.io.Reader; public class ReadFromFile {
/**
* 以字节为单位读取文件,常用于读二进制文件,如图片、声音、影像等文件。
*
* @param fileName
* 文件的名
*/
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) {
}
}
}
} /**
* 以字符为单位读取文件,常用于读文本,数字等类型的文件
*
* @param fileName
* 文件名
*/
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下,rn这两个字符在一起时,表示一个换行。
// 但如果这两个字符分开显示时,会换两次行。
// 因此,屏蔽掉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) {
}
}
}
} /**
* 以行为单位读取文件,常用于读面向行的格式化文件
*
* @param fileName
* 文件名
*/
public static void readFileByLines(String fileName) {
File file = new File(fileName);
System.out.println(file.getAbsolutePath());
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) {
}
}
}
} /**
* 随机读取文件内容
*
* @param fileName
* 文件名
*/
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) {
}
}
}
} /**
* 显示输入流中还剩的字节数
*
* @param in
*/
private static void showAvailableBytes(InputStream in) {
try {
System.out.println("当前字节输入流中的字节数为:" + in.available());
} catch (IOException e) {
e.printStackTrace();
}
}
}

转载请注明出处!谢谢!

java 文件和流的更多相关文章

  1. Java - 文件(IO流)

    Java - 文件 (IO)   流的分类:     > 文件流:FileInputStream | FileOutputStream | FileReader | FileWriter     ...

  2. java 文件及流读取

    在Java语言的IO编程中,读取文件是分两个步骤:1.将文件中的数据转换为流,2.读取流内部的数据.其中第一个步骤由系统完成,只需要创建对应的流对象即可,对象创建完成以后步骤1就完成了,第二个步骤使用 ...

  3. Java:文件字符流和字节流的输入和输出

    最近在学习Java,所以就总结一篇文件字节流和字符流的输入和输出. 总的来说,IO流分类如下: 输入输出方向:     输入流(从外设读取到内存)和输出流(从内存输出到外设) 数据的操作方式: 字节流 ...

  4. Java文件IO流的操作总结

    Java中的IO操作涉及到的概念及相关类很多,很容易弄混,今天特来整理总结一下,并附上一份完整的文件操作的代码. 概念解析 读和写 流就是管道,向管道里面写数据用输出流:write 从管道里面读数据, ...

  5. Java文件字符流

    1.字符编码(Character encoding)和编码集(Character set) 字符编码(Character encoding)是将字符转为字节或字节数组的过程. 字符集(Characte ...

  6. Java学习笔记-Java文件操作流

     day03 输入输出流:读入写出  节点流:   有明确的来源和去向   往往对字节操作 节点流又叫低级流.字节流   处理流:  没有明确的来源和去向  往往对低级流或其他高级流进行操作,不能独立 ...

  7. Java文件与流测试

    import java.io.File; import java.io.InputStreamReader; import java.math.BigDecimal; import java.io.B ...

  8. java文件与流课后作业

    1,编写一个程序,指定一个文件夹,能自动计算出其总容量, 2,编写一个文件加解密程序,通过命令行完成加解密工作3,编写一个文件分割工具,能把一个大文件分割成多个小的文件.并且能再次把它们合并起来得到完 ...

  9. Java IO 文件与流基础

    Java IO 文件与流基础 @author ixenos 摘要:创建文件.文件过滤.流分类.流结构.常见流.文件流.字节数组流(缓冲区) 如何创建一个文件 #当我们调用File类的构造器时,仅仅是在 ...

随机推荐

  1. 嵌套滚动demo

    https://github.com/luv135/NestedScrollingDemo https://github.com/ggajews/nestedscrollingchildviewdem ...

  2. GDI+编程说明及小结

    原文地址:http://blog.csdn.net/byxdaz/article/details/5972759 GDI+(Graphics Device Interface Plus图形设备接口加) ...

  3. 如用使用高版本framework,比如支持iOS5及以上的工程中使用Social.framework

    在Targets -> Build Phases里的 Link Binary With Libraries项中,将高版本的framework,如Social.framework 设置成Optio ...

  4. sharepoint 2010 列表数据分页控件介绍 pagination UserControl

    转:http://blog.csdn.net/chenxinxian/article/details/8714391 这里主要是介绍下最近开发的一个sharepoint列表或者文档库的分页控件,并且把 ...

  5. Android-adb shell 读取手机系统文件

    1.首先保证手机是root 状态 2.运行 adb shell 页面以后 su root 3.ls 就会发现目录结构可以显示了

  6. HDOJ --- 2577

    How to Type Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others) Total S ...

  7. HDU-3790 最短路径问题

    最短路径问题 Time Limit : 2000/1000ms (Java/Other)   Memory Limit : 32768/32768K (Java/Other) Total Submis ...

  8. HDU-- Buy Tickets

    告知每次要插到第 i 个位置上,问最后它们的顺序是什么. 这一题,不是考线段树,是考如何想出用线段树...思维很巧妙,倒过来做的话就能确定此人所在的位置....   Buy Tickets Time ...

  9. JavaScript---网络编程(10)--DHTML技术演示(3)-多选框

    这节讲述多选框的使用,当然,肯定是结合css和Javascript一起的. checkbox的使用1: 演示代码: <html> <head> <meta http-eq ...

  10. 初识chromium thread的实现

    接触chromium已有一段时间,写点东西学习一下吧. 首先说一下用法,如何利用chromium封装好的thread类来开一个线程.在base里有一个封装该类的头文件thread.h,include它 ...