java對象流,java對象流與字節流

本文目錄一覽:

java中怎麼克隆對象流

先將要克隆的對象序列化,也就是實現java.io.Serializable接口,然後再複製。你這個問題也就是類型轉換的問題,要看具體情況了,呵呵,不好意思,希望不會添亂

Java中有幾種類型的流

在Java.io包中還有許多其他的流,主要是為了提高性能和使用方便。C/C++只能提供字節流。Java中的流分為兩種,一種是字節流,另一種是字符流,分別由四個抽象類來表示(每種流包括輸入和輸出兩種所以一共四個):InputStream,OutputStream,Reader,Writer。Java中其他多種多樣變化的流均是由它們派生出來的.

字符流和字節流是根據處理數據的不同來區分的。字節流按照8位傳輸,字節流是最基本的,所有文件的儲存是都是字節(byte)的儲存,在磁盤上保留的並不是文件的字符而是先把字符編碼成字節,再儲存這些字節到磁盤。

1.字節流可用於任何類型的對象,包括二進制對象,而字符流只能處理字符或者字符串;

2. 字節流提供了處理任何類型的IO操作的功能,但它不能直接處理Unicode字符,而字符流就可以。

讀文本的時候用字符流,例如txt文件。讀非文本文件的時候用字節流,例如mp3。理論上任何文件都能夠用字節流讀取,但當讀取的是文本數據時,為了能還原成文本你必須再經過一個轉換的工序,相對來說字符流就省了這個麻煩,可以有方法直接讀取。

字符流處理的單元為2個字節的Unicode字符,分別操作字符、字符數組或字符串,而字節流處理單元為1個字節, 操作字節和字節數組。所以字符流是由Java虛擬機將字節轉化為2個字節的Unicode字符為單位的字符而成的,所以它對多國語言支持性比較好!

1.字節流:繼承於InputStream \ OutputStream。

OutputStream提供的方法:

void write(int b):寫入一個字節的數據

void write(byte[] buffer):將數組buffer的數據寫入流

void write(byte[] buffer,int offset,int len):從buffer[offset]開始,寫入len個字節的數據

void flush():強制將buffer內的數據寫入流

void close():關閉流

InputStream提供的方法:

int read():讀出一個字節的數據,如果已達文件的末端,返回值為-1

int read(byte[] buffer):讀出buffer大小的數據,返回值為實際所讀出的字節數

int read(byte[] buffer,int offset,int len)

int available():返迴流內可供讀取的字節數目

long skip(long n):跳過n個字節的數據,返回值為實際所跳過的數據數

void close():關閉流

2.字符流,繼承於InputStreamReader \ OutputStreamWriter。

字符流的類:1),BufferedReader是一種過濾器(filter)(extends FilterReader)。過濾

器用來將流的數據加以處理再輸出。構造函數為:

BufferedReader(Reader in):生成一個緩衝的字符輸入流,in為一個讀取器

BufferedReader(Reader in,int size):生成一個緩衝的字符輸入流,並指定緩衝區的大小為size

public class IOStreamDemo {

public void samples() throws IOException { //1. 這是從鍵盤讀入一行數據,返回的是一個字符串

BufferedReader stdin =new BufferedReader(new InputStreamReader(System.in));

System.out.print(”Enter a line:”);

System.out.println(stdin.readLine());

//2. 這是從文件中逐行讀入數據

BufferedReader in = new BufferedReader(new FileReader(”IOStreamDemo.java”));

String s, s2 = new String();

while((s = in.readLine())!= null)

s2 += s + “\n”;

in.close();

//3. 這是從一個字符串中逐個讀入字節

StringReader in1 = new StringReader(s2);

int c;

while((c = in1.read()) != -1)

System.out.print((char)c);

//4. 這是將一個字符串寫入文件

try {

BufferedReader in2 = new BufferedReader(new StringReader(s2));

PrintWriter out1 = new PrintWriter(new BufferedWriter(new FileWriter(”IODemo.out”)));

int lineCount = 1;

while((s = in2.readLine()) != null )

out1.println(lineCount++ + “: ” + s);

out1.close();

} catch(EOFException e) {

System.err.println(”End of stream”);

}

} }

對於上面的例子,需要說明的有以下幾點:

1. InputStreamReader是InputStream和Reader之間的橋樑,由於System.in是字節流,需要用它來包裝之後變為字符流供給BufferedReader使用。

3. PrintWriter out1 = new PrintWriter(new BufferedWriter(new FileWriter(”IODemo.out”)));

這句話體現了Java輸入輸出系統的一個特點,為了達到某個目的,需要包裝好幾層。首先,輸出目的地是文件IODemo.out,所以最內層包裝的是FileWriter,建立一個輸出文件流,接下來,我們希望這個流是緩衝的,所以用BufferedWriter來包裝它以達到目的,最後,我們需要格式化輸出結果,於是將PrintWriter包在最外層。

Java流有着另一個重要的用途,那就是利用對象流對對象進行序列化。

在一個程序運行的時候,其中的變量數據是保存在內存中的,一旦程序結束這些數據將不會被保存,一種解決的辦法是將數據寫入文件,而Java中提供了一種機制,它可以將程序中的對象寫入文件,之後再從文件中把對象讀出來重新建立。這就是所謂的對象序列化。Java中引入它主要是為了RMI(Remote

Method Invocation)和Java Bean所用,不過在平時應用中,它也是很有用的一種技術。

Java 如何對文件進行多個Object對象流的讀寫操作

思路:把已經序列化的對象存入容器(如LinkedList?)中,然後用ObjectInputStream和ObjectOutputStream對這個實例化的LinkedList?對象進行讀寫。測試主程序:/** * @Title: FileRW.java * @Package com.file * @Description: 文件、文件夾的創建、寫入練習。讀寫是使用對象流實現。 * @author 慢跑學Android * @date 2011-11-19 下午03:53:01 * @version V1.0 */ package com.file; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.util.LinkedList; public class FileRW { private String dirPath; private String filename; public static void main(String[] args) { String path = “C:\\曉聲”; String fileName = “test.txt”; FileRW fileRW = new FileRW(path, fileName); LinkedListTestMessage msgOut = new LinkedListTestMessage(); LinkedListTestMessage msgIn = null; msgOut.add(new TestMessage(“柯南”, “偶像”)); msgOut.add(new TestMessage(“卡卡西”, “好樣的”)); msgOut.add(new TestMessage(“Android”, “Android”)); msgOut.add(new TestMessage(“哈哈”, “測試下喔”)); fileRW.writeObject(path, fileName, msgOut); msgIn = fileRW.readObject(path,fileName); for(TestMessage temp:msgIn) { System.out.println(temp.getName() + temp.getData()); } } public FileRW(String dirPath, String filename) { this.dirPath = dirPath; this.filename = filename; if (creatDir()) { creatFile(); } } private boolean creatDir() { if (null != dirPath) { File path = new File(dirPath); if (path.exists()) { return true; } if (true == path.mkdirs() ) { return true; } } return false; } private void creatFile() { if (null != filename) { File file = new File(dirPath, filename); if (false == file.exists()) { try { file.createNewFile(); } catch (IOException e) { e.printStackTrace(); } } } } /** * @Title: writeObject * @Description: Write a object to a file. * @param path the directory of the target file * @param filename the name of the target file * @param msg the type of the object * @return void * @throws */ private void writeObject(String path, String filename, LinkedListTestMessage msg) { File file = new File(path, filename); if (false == file.isFile()) { return ; } try { // The value “false” for FileOutputStream means that overwrite this file, // if it is “true”,append the new data to this file. ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(file,false)); oos.writeObject(msg); oos.flush(); oos.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } /** * @Title: readObject * @Description: Read a object from a file. * @param path the directory of the target file * @param filename the name of the target file * @return LinkedListTestMessage * @throws */ @SuppressWarnings(“unchecked”) private LinkedListTestMessage readObject(String path, String filename) { File file = new File(path, filename); ObjectInputStream ois = null; LinkedListTestMessage msgAll = null; try { ois = new ObjectInputStream(new FileInputStream(file)); try { msgAll = (LinkedListTestMessage)ois.readObject(); } catch (ClassNotFoundException e) { e.printStackTrace(); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { try { ois.close(); } catch (IOException e) { e.printStackTrace(); } } return msgAll; } } 測試程序中的消息包定義:/** * @Title: TestMessage.java * @Package com.file * @Description: FileRW的消息流 * @author 慢跑學Android * @date 2011-11-19 下午04:35:11 * @version V1.0 */ package com.file; public class TestMessage implements java.io.Serializable { private String name; private String data; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getData() { return data; } public void setData(String data) { this.data = data; } public TestMessage(String name, String msg) { this.name = name; data = msg; } } 程序運行結果:參考資料:ObjectInputStream類和ObjectOutputStream類的使用

java中當使用對象流寫入或讀入對象時,要保證對象是序列化的嗎?

對象以流傳輸時必須要使用序列化,否則無法寫入文件,或從文件中反序列化回來。

實例方法當然可以調用靜態變量了

java中如果沒有序列化,那麼對對象流進行讀寫操作會引發什麼問題?

運行時會報錯的,類必須實現了Serializable接口,才能被序列化和反序列化,可以以流的形式存儲

JAVA對象流的作用是什麼?

對象流作用就是要對類的對象進行保存和讀取,使其能夠只動進行!

原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-hant/n/196838.html

(0)
打賞 微信掃一掃 微信掃一掃 支付寶掃一掃 支付寶掃一掃
小藍的頭像小藍
上一篇 2024-12-03 13:26
下一篇 2024-12-03 13:26

相關推薦

  • java client.getacsresponse 編譯報錯解決方法

    java client.getacsresponse 編譯報錯是Java編程過程中常見的錯誤,常見的原因是代碼的語法錯誤、類庫依賴問題和編譯環境的配置問題。下面將從多個方面進行分析…

    編程 2025-04-29
  • Java JsonPath 效率優化指南

    本篇文章將深入探討Java JsonPath的效率問題,並提供一些優化方案。 一、JsonPath 簡介 JsonPath是一個可用於從JSON數據中獲取信息的庫。它提供了一種DS…

    編程 2025-04-29
  • Java Bean加載過程

    Java Bean加載過程涉及到類加載器、反射機制和Java虛擬機的執行過程。在本文中,將從這三個方面詳細闡述Java Bean加載的過程。 一、類加載器 類加載器是Java虛擬機…

    編程 2025-04-29
  • Java騰訊雲音視頻對接

    本文旨在從多個方面詳細闡述Java騰訊雲音視頻對接,提供完整的代碼示例。 一、騰訊雲音視頻介紹 騰訊雲音視頻服務(Cloud Tencent Real-Time Communica…

    編程 2025-04-29
  • Java Milvus SearchParam withoutFields用法介紹

    本文將詳細介紹Java Milvus SearchParam withoutFields的相關知識和用法。 一、什麼是Java Milvus SearchParam without…

    編程 2025-04-29
  • Java 8中某一周的周一

    Java 8是Java語言中的一個版本,於2014年3月18日發布。本文將從多個方面對Java 8中某一周的周一進行詳細的闡述。 一、數組處理 Java 8新特性之一是Stream…

    編程 2025-04-29
  • Java判斷字符串是否存在多個

    本文將從以下幾個方面詳細闡述如何使用Java判斷一個字符串中是否存在多個指定字符: 一、字符串遍歷 字符串是Java編程中非常重要的一種數據類型。要判斷字符串中是否存在多個指定字符…

    編程 2025-04-29
  • VSCode為什麼無法運行Java

    解答:VSCode無法運行Java是因為默認情況下,VSCode並沒有集成Java運行環境,需要手動添加Java運行環境或安裝相關插件才能實現Java代碼的編寫、調試和運行。 一、…

    編程 2025-04-29
  • Java任務下發回滾系統的設計與實現

    本文將介紹一個Java任務下發回滾系統的設計與實現。該系統可以用於執行複雜的任務,包括可回滾的任務,及時恢復任務失敗前的狀態。系統使用Java語言進行開發,可以支持多種類型的任務。…

    編程 2025-04-29
  • Java 8 Group By 會影響排序嗎?

    是的,Java 8中的Group By會對排序產生影響。本文將從多個方面探討Group By對排序的影響。 一、Group By的概述 Group By是SQL中的一種常見操作,它…

    編程 2025-04-29

發表回復

登錄後才能評論