Java InputStream 和OutputStream

来源:互联网 发布:织梦cms gbk utf8 编辑:程序博客网 时间:2024/05/02 23:22
一、OutputStream用法:

    1、OutputStream类是Java IO API中所有输出流的基类。子类包括BufferedOutputStream,FileOutputStream等等

BufferedOutputStream: 提供了缓冲功能的输出流,在写出完成之前要调用flush来保证数据的输出。

DataOutputStream: 数据输出流允许应用程序以适当方式将基本 Java 数据类型写入输出流中。然后,应用程序可以使用数据输入流将数据读入。

PipedOutputStream: 允许以管道的方式来处理流。可以将管道输出流连接到管道输入流来创建通信管道。管道输出流是管道的发送端。通常,数据由某个线程写入PipedOutputStream对象,并由其他线程从连接的 PipedInputStream读取。

PrintStream: 为其他输出流添加了功能,使它们能够方便地打印各种数据值表示形式。我们经常用到的System.out或者System.err都是PrintStream。


    2、主要函数:

write(byte[])

OutputStream同样包含了将字节数据中全部或者部分数据写入到输出流中的方法,分别是write(byte[])和write(byte[], int offset, int length)。

write(byte[])把字节数组中所有数据写入到输出流中。

write(byte[], int offset, int length)把字节数据中从offset位置开始,length个字节的数据写入到输出流。

flush()

OutputStream的flush()方法将所有写入到OutputStream的数据冲刷到相应的目标媒介中。比如,如果输出流是FileOutputStream,那么写入到其中的数据可能并没有真正写入到磁盘中。即使所有数据都写入到了FileOutputStream,这些数据还是有可能保留在内存的缓冲区中。通过调用flush()方法,可以把缓冲区内的数据刷新到磁盘(或者网络,以及其他任何形式的目标媒介)中。

close()

当你结束数据写入时,需要关闭OutputStream。通过调用close()可以达到这一点。因为OutputStream的各种write()方法可能会抛出IO异常,所以你需要把调用close()的关闭操作方在finally块中执行。


    3、主要说明 Write() 函数的用法:

(1)void write(byte[] b):将 b.length 个字节从指定的 byte 数组写入此输出流。
(2)void write(byte[] b, int off, int len):将指定 byte 数组中从偏移量 off 开始的 len 个字节写入此输出流。
(3)abstract  void write(int b):将指定的字节写入此输出流。

实例:
(1)向指定文件写入“hello world!

public void setHelloWorldToFile() throws IOException{
String filePath = "E:"+  File.separator +"test.txt";
if (!file.exists()){
file.createNewFile();
}
OutputStream out = new FileOutputStream(filePath);
String str = "hello world!";

out.write(str.getBytes()); // write(byte[] b)
out.close();
}

(2)将 InputStream 转化为 byte[]

 public byte[] readBytes(InputStream in) throws IOException {
        BufferedInputStream bufin = new BufferedInputStream(in);
        int buffSize = 1024;
        ByteArrayOutputStream out = new ByteArrayOutputStream(buffSize);
 
        byte[] temp = new byte[buffSize];
        int size = 0;
        while ((size = bufin.read(temp)) != -1) {
            out.write(temp, 0, size);
        }
        bufin.close();
 
        byte[] content = out.toByteArray();
        return content;
 }

(3)InputStream读取和写入文件操作

public byte[] readBytes() throws IOException {
// 将File文件转化为 InputStream
File file = new File("file.xml");
InputStream inputStream = new FileInputStream(file);

// 创建新的File文件
String filePath = "E:" + File.separator + "test.txt";
if (!file.exists()){
file.createNewFile();
}
OutputStream outputStream = new FileOutputStream("E:"+  File.separator +"test.txt");
int byteCount = 0;
byte[] bytes = new byte[1024];
while ((byteCount = inputStream.read(bytes, 0, 1024)) != -1)  // 当数据流读取到最后时,返回 -1
{
outputStream.write(bytes, 0, byteCount);
}
inputStream.close();
outputStream.close();
}


二、InputStream 的用法:

    1、

BufferedInputStream: 提供了缓冲功能。

DataInputStream: 允许应用程序以与机器无关方式从底层输入流中读取基本 Java 数据类型。应用程序可以使用数据输出流写入稍后由数据输入流读取的数据。

PipedInputStream: 允许以管道的方式来处理流。当连接到一个PipedOutputStream后,它会读取后者输出到管道的数据。

PushbackInputStream: 允许放回已经读取的数据。

SequenceInputStream: 能对多个inputstream进行顺序处理。


读取:

CharArrayReader: 从内存中的字符数组中读入数据,以对数据进行流式读取。

StringReader:从内存中的字符串读入数据,以对数据进行流式读取。

FileReader:从文件中读入数据。注意这里读入数据时会根据JVM的默认编码对数据进行内转换,而不能指定使用的编码。所以当文件使用的编 码不是JVM默认编码时,不要使用这种方式。要正确地转码,使用InputStreamReader。


BufferedReader:提供缓冲功能,可以读取行:readLine();

LineNumberReader: 提供读取行的控制:getLineNumber()等方法。

InputStreamReader: 字节流通向字符流的桥梁:它使用指定的 charset读取字节并将其解码为字符。



实例:

1、java读取文件内容到字符串

    /**

     * 将文本文件中的内容读入到buffer中

     * @param buffer buffer

     * @param filePath 文件路径

     * @throws IOException 异常

     */

    public static void readToBuffer(StringBuffer buffer, String filePath) throws IOException {

        InputStream is = new FileInputStream(filePath);

        String line; // 用来保存每行读取的内容

        BufferedReader reader = new BufferedReader(new InputStreamReader(is));

        line = reader.readLine(); // 读取第一行

        while (line != null) { // 如果 line 为空说明读完了

            buffer.append(line); // 将读到的内容添加到 buffer 中

            buffer.append("\n"); // 添加换行符

            line = reader.readLine(); // 读取下一行

        }

        reader.close();

        is.close();

    }

    /**

     * 读取文本文件内容

     * @param filePath 文件所在路径

     * @return 文本内容

     * @throws IOException 异常

     */

    public static String readFile(String filePath) throws IOException { 

        StringBuffer sb = new StringBuffer();

        readToBuffer(sb, filePath);

        return sb.toString();

    }

执行:readFile("C:\MapGIS 10\IGServer for Java\IGServer\data\temp\70ea5522-ca05-45cf-bd3d-1af7f5e0248b\template.xml")


2、把一个文件夹中的所有文件复制到另一个文件夹中

public void copy(String originDirectory,String targetDirectory){
File origindirectory = new File(originDirectory);   //源路径File实例
File targetdirectory = new File(targetDirectory);  //目标路径File实例
if(!origindirectory.isDirectory() || !targetdirectory.isDirectory()){    //判断是不是正确的路径
System.out.println("不是正确的目录!");
return;
}
File[] fileList = origindirectory.listFiles();  //目录中的所有文件
for(File file : fileList){
if(!file.isFile())   //判断是不是文件
continue;
System.out.println(file.getName());
try{
FileInputStream fin = new FileInputStream(file);
BufferedInputStream bin = new BufferedInputStream(fin);
PrintStream pout = new PrintStream(targetdirectory.getAbsolutePath()+"/"+file.getName());
BufferedOutputStream bout = new BufferedOutputStream(pout);
int total =bin.available();  //文件的总大小
int percent = total/100;    //文件总量的百分之一
int count;
while((count = bin.available())!= 0){
int c = bin.read();  //从输入流中读一个字节
bout.write((char)c);  //将字节(字符)写到输出流中
if(((total-count) % percent) == 0){
double d = (double)(total-count) / total; //必须强制转换成double
System.out.println(Math.round(d*100)+"%"); //输出百分比进度
}
}
bout.close();
pout.close();
bin.close();
fin.close();
}catch(IOException e){
e.printStackTrace();
}
}
System.out.println("End");
}
















0 0