欧美一区二区三区老妇人-欧美做爰猛烈大尺度电-99久久夜色精品国产亚洲a-亚洲福利视频一区二区

java快速io代碼模版 java io源碼

java 代碼關(guān)于IO 的,高手幫忙解答 這個(gè)代碼實(shí)現(xiàn)什么功能??

in.read()是讀取一個(gè)數(shù)據(jù)字節(jié)的意思,返回的是0~255的int型數(shù)據(jù),在你這個(gè)代碼里面可以任意輸入,

創(chuàng)新互聯(lián)主營嘉蔭網(wǎng)站建設(shè)的網(wǎng)絡(luò)公司,主營網(wǎng)站建設(shè)方案,成都App制作,嘉蔭h5微信平臺(tái)小程序開發(fā)搭建,嘉蔭網(wǎng)站營銷推廣歡迎嘉蔭等地區(qū)企業(yè)咨詢

(char)i則是將剛剛讀取的int型字節(jié)強(qiáng)制轉(zhuǎn)換成char型的,而且你的代碼那個(gè)構(gòu)造函數(shù)有錯(cuò),就是打錯(cuò)了

下面是你的代碼我把那個(gè)小錯(cuò)給你改了,還有你把 System.out.print(c);換成 System.out.println(c);就會(huì)更好的理解in.read()了

import java.io.InputStream;

import java.io.IOException;

public class test{

public test(InputStream in){

try{

while(true)

{

int i=in.read();

char c=(char)i;

System.out.println(c);

}

}catch(IOException e){

System.out.print(e);

}

}

public static void main(String[] args){

new test(System.in);

}

}

java軟件開發(fā)的代碼規(guī)范

1、組織與風(fēng)格

(1).關(guān)鍵詞和操作符之間加適當(dāng)?shù)目崭瘛?/p>

(2).相對(duì)獨(dú)立的程序塊與塊之間加空行

(3).較長的語句、表達(dá)式等要分成多行書寫。

(4).劃分出的新行要進(jìn)行適應(yīng)的縮進(jìn),使排版整齊,語句可讀。

(5).長表達(dá)式要在低優(yōu)先級(jí)操作符處劃分新行,操作符放在新行之首。

(6).循環(huán)、判斷等語句中若有較長的表達(dá)式或語句,則要進(jìn)行適應(yīng)的劃分。

(7).若函數(shù)或過程中的參數(shù)較長,則要進(jìn)行適當(dāng)?shù)膭澐帧?/p>

(8).不允許把多個(gè)短語句寫在一行中,即一行只寫一條語句。

(9).函數(shù)或過程的開始、結(jié)構(gòu)的定義及循環(huán)、判斷等語句中的代碼都要采用縮進(jìn)風(fēng)格。

注:如果大家有興趣可以到安安DIY創(chuàng)作室博客,有相關(guān)說明性的文章和解釋。

2、注解

Java 的語法與 C++ 及為相似,那么,你知道 Java 的注釋有幾種嗎?是兩種?

// 注釋一行

/* ...... */ 注釋若干行

不完全對(duì),除了以上兩種之外,還有第三種,文檔注釋:

/** ...... */ 注釋若干行,并寫入 javadoc 文檔

注釋要簡(jiǎn)單明了。

String userName = null; //用戶名

邊寫代碼邊注釋,修改代碼同時(shí)修改相應(yīng)的注釋,以保證注釋與代碼的一致性。

在必要的地方注釋,注釋量要適中。注釋的內(nèi)容要清楚、明了,含義準(zhǔn)確,防止注釋二義性。

保持注釋與其描述的代碼相鄰,即注釋的就近原則。

對(duì)代碼的注釋應(yīng)放在其上方相鄰位置,不可放在下面。對(duì)數(shù)據(jù)結(jié)構(gòu)的注釋應(yīng)放在其上方相鄰位置,不可放在下面;對(duì)結(jié)構(gòu)中的每個(gè)域的注釋應(yīng)放在此域的右方;

同一結(jié)構(gòu)中不同域的注釋要對(duì)齊。

變量、常量的注釋應(yīng)放在其上方相鄰位置或右方。

全局變量要有較詳細(xì)的注釋,包括對(duì)其功能、取值范圍、哪些函數(shù)或過程存取它以及存取時(shí)注意事項(xiàng)等的說明。

在每個(gè)源文件的頭部要有必要的注釋信息,包括:文件名;版本號(hào);作者;生成日期;模塊功能描述(如功能、主要算法、內(nèi)部各部分之間的關(guān)系、該文件與其它文件關(guān)系等);主要函數(shù)或過程清單及本文件歷史修改記錄等。

/**

* Copy Right Information : Neusoft IIT

* Project : eTrain

* JDK version used : jdk1.3.1

* Comments : config path

* Version : 1.01

* Modification history :2003.5.1

* Sr Date Modified By Why What is modified

* 1. 2003.5.2 Kevin Gao new

**/

在每個(gè)函數(shù)或過程的前面要有必要的注釋信息,包括:函數(shù)或過程名稱;功能描述;輸入、輸出及返回值說明;調(diào)用關(guān)系及被調(diào)用關(guān)系說明等

/**

* Description :checkout 提款

* @param Hashtable cart info

* @param OrderBean order info

* @return String

*/

public String checkout(Hashtable htCart,

OrderBean orderBean)

throws Exception{

}

javadoc注釋標(biāo)簽語法

@author 對(duì)類的說明 標(biāo)明開發(fā)該類模塊的作者

@version 對(duì)類的說明 標(biāo)明該類模塊的版本

@see 對(duì)類、屬性、方法的說明 參考轉(zhuǎn)向,也就是相關(guān)主題

@param 對(duì)方法的說明 對(duì)方法中某參數(shù)的說明

@return 對(duì)方法的說明 對(duì)方法返回值的說明

@exception 對(duì)方法的說明 對(duì)方法可能拋出的異常進(jìn)行說明

3、命名規(guī)范

定義這個(gè)規(guī)范的目的是讓項(xiàng)目中所有的文檔都看起來像一個(gè)人寫的,增加可讀性,減少項(xiàng)目組中因?yàn)閾Q人而帶來的損失。(這些規(guī)范并不是一定要絕對(duì)遵守,但是一定要讓程序有良好的可讀性)較短的單詞可通過去掉元音形成縮寫;要不然最后自己寫的代碼自己都看不懂了,那可不行。

較長的單詞可取單詞的頭幾發(fā)符的優(yōu)先級(jí),并用括號(hào)明確表達(dá)式的操作順序,避免使用默認(rèn)優(yōu)先級(jí)。

使用匈牙利表示法

Package 的命名

Package 的名字應(yīng)該都是由一個(gè)小寫單詞組成。

package com.neu.util

Class 的命名

Class 的名字必須由大寫字母開頭而其他字母都小寫的單詞組成,對(duì)于所有標(biāo)識(shí)符,其中包含的所有單詞都應(yīng)緊靠在一起,而且大寫中間單詞的首字母。

public class ThisAClassName{}

Class 變量的命名

變量的名字必須用一個(gè)小寫字母開頭。后面的單詞用大寫字母開頭

userName , thisAClassMethod

Static Final 變量的命名

static Final 變量的名字應(yīng)該都大寫,并且指出完整含義。

/**

*DBConfig PATH

**/

public static final String

DB_CONFIG_FILE_PATH =com.neu.etrain.dbconfig;

參數(shù)的命名

參數(shù)的名字必須和變量的命名規(guī)范一致。

數(shù)組的命名

數(shù)組應(yīng)該總是用下面的方式來命名:

byte[] buffer;

而不是:

byte buffer[];

方法的參數(shù)

使用有意義的參數(shù)命名,如果可能的話,使用和要賦值的字段一樣的名字:

SetCounter(int size){

this.size = size;

}

4、文件樣式

所有的 Java(*.java) 文件都必須遵守如下的樣式規(guī)則:

版權(quán)信息

版權(quán)信息必須在 java 文件的開頭,比如:

/*

* Copyright ? 2000 Shanghai XXX Co. Ltd.

* All right reserved.

*/

其他不需要出現(xiàn)在 javadoc 的信息也可以包含在這里。

Package/Imports

package 行要在 import 行之前,import 中標(biāo)準(zhǔn)的包名要在本地的包名之前,而且按照字母

順序排列。如果 import 行中包含了同一個(gè)包中的不同子目錄,則應(yīng)該用 * 來處理。

package hotlava.net.stats;

import java io.*;

import java.util.Observable;

import hotlava.util.Application;

這里 java。io.* 使用來代替InputStream and OutputStream 的。

Class

接下來的是類的注釋,一般是用來解釋類的。

/**

* A class representing a set of packet and byte counters

* It is observable to allow it to be watched, but only

* reports changes when the current set is complete

*/

接下來是類定義,包含了在不同的行的 extends 和 implements

public class CounterSet

extends Observable

implements Cloneable

Class Fields

接下來是類的成員變量:

/**

* Packet counters

*/

protected int[] packets;

public 的成員變量必須生成文檔(JavaDoc)。proceted、private和 package 定義的成

員變量如果名字含義明確的話,可以沒有注釋。

存取方法

接下來是類變量的存取的方法。它只是簡(jiǎn)單的用來將類的變量賦值獲取值的話,可以簡(jiǎn)單的

寫在一行上。

/**

* Get the counters

* @return an array containing the statistical data. This array has been

* freshly allocated and can be modified by the caller.

*/

public int[] getPackets() { return copyArray(packets, offset); }

public int[] getBytes() { return copyArray(bytes, offset); }

public int[] getPackets() { return packets; }

public void setPackets(int[] packets) { this.packets = packets; }

其它的方法不要寫在一行上

構(gòu)造函數(shù)

接下來是構(gòu)造函數(shù),它應(yīng)該用遞增的方式寫(比如:參數(shù)多的寫在后面)。

訪問類型 (public, private 等.) 和 任何 static, final 或 synchronized 應(yīng)該在一行

中,并且方法和參數(shù)另寫一行,這樣可以使方法和參數(shù)更易讀。

public

CounterSet(int size){

this.size = size;

}

克隆方法

如果這個(gè)類是可以被克隆的,那么下一步就是 clone 方法:

public

Object clone() {

try {

CounterSet obj = (CounterSet)super.clone();

obj.packets = (int[])packets.clone();

obj.size = size;

return obj;

}catch(CloneNotSupportedException e) {

throw new InternalError(Unexpected CloneNotSUpportedException: +

e.getMessage());

}

}

類方法

下面開始寫類的方法:

/**

* Set the packet counters

* (such as when restoring from a database)

*/

protected final

void setArray(int[] r1, int[] r2, int[] r3, int[] r4)

throws IllegalArgumentException

{

//

// Ensure the arrays are of equal size

//

if (r1.length != r2.length || r1.length != r3.length || r1.length != r4.length)

throw new IllegalArgumentException(Arrays must be of the same size);

System.arraycopy(r1, 0, r3, 0, r1.length);

System.arraycopy(r2, 0, r4, 0, r1.length);

}

toString 方法

無論如何,每一個(gè)類都應(yīng)該定義 toString 方法:

public

String toString() {

String retval = CounterSet: ;

for (int i = 0; i data.length(); i++) {

retval += data.bytes.toString();

retval += data.packets.toString();

}

return retval;

}

}

main 方法

如果main(String[]) 方法已經(jīng)定義了, 那么它應(yīng)該寫在類的底部.

5、代碼可讀性

避免使用不易理解的數(shù)字,用有意義的標(biāo)識(shí)來替代。

不要使用難懂的技巧性很高的語句。

源程序中關(guān)系較為緊密的代碼應(yīng)盡可能相鄰。

6、代碼性能

在寫代碼的時(shí)候,從頭至尾都應(yīng)該考慮性能問題。這不是說時(shí)間都應(yīng)該浪費(fèi)在優(yōu)化代碼上,而是我們時(shí)刻應(yīng)該提醒自己要注意代碼的效率。比如:如果沒有時(shí)間來實(shí)現(xiàn)一個(gè)高效的算法,那么我們應(yīng)該在文檔中記錄下來,以便在以后有空的時(shí)候再來實(shí)現(xiàn)她。

不是所有的人都同意在寫代碼的時(shí)候應(yīng)該優(yōu)化性能這個(gè)觀點(diǎn)的,他們認(rèn)為性能優(yōu)化的問題應(yīng)該在項(xiàng)目的后期再去考慮,也就是在程序的輪廓已經(jīng)實(shí)現(xiàn)了以后。

不必要的對(duì)象構(gòu)造

不要在循環(huán)中構(gòu)造和釋放對(duì)象

使用 StringBuffer 對(duì)象

在處理 String 的時(shí)候要盡量使用 StringBuffer 類,StringBuffer 類是構(gòu)成 String 類的基礎(chǔ)。

String 類將 StringBuffer 類封裝了起來,(以花費(fèi)更多時(shí)間為代價(jià))為開發(fā)人員提供了一個(gè)安全的接口。當(dāng)我們?cè)跇?gòu)造字符串的時(shí)候,我們應(yīng)該用 StringBuffer 來實(shí)現(xiàn)大部分的工作,當(dāng)工作完成后將 StringBuffer 對(duì)象再轉(zhuǎn)換為需要的 String 對(duì)象。比如:如果有一個(gè)字符串必須不斷地在其后添加許多字符來完成構(gòu)造,那么我們應(yīng)該使用StringBuffer 對(duì)象和她的 append() 方法。如果我們用 String 對(duì)象代替StringBuffer 對(duì)象的話,會(huì)花費(fèi)許多不必要的創(chuàng)建和釋放對(duì)象的 CPU 時(shí)間。大家可以來安安DIY創(chuàng)作室一起討論。

避免太多的使用 synchronized 關(guān)鍵字避免不必要的使用關(guān)鍵字 synchronized,應(yīng)該在必要的時(shí)候再使用她,這是一個(gè)避免死鎖的好方法。

7、編程技巧

byte 數(shù)組轉(zhuǎn)換到 characters

為了將 byte 數(shù)組轉(zhuǎn)換到 characters,你可以這么做:

Hello world!.getBytes();

Utility 類

Utility 類(僅僅提供方法的類)應(yīng)該被申明為抽象的來防止被繼承或被初始化。

初始化

下面的代碼是一種很好的初始化數(shù)組的方法:

objectArguments = new Object[] { arguments };

枚舉類型

JAVA 對(duì)枚舉的支持不好,但是下面的代碼是一種很有用的模板:

class Colour {

public static final Colour BLACK = new Colour(0, 0, 0);

public static final Colour RED = new Colour(0xFF, 0, 0);

public static final Colour GREEN = new Colour(0, 0xFF, 0);

public static final Colour BLUE = new Colour(0, 0, 0xFF);

public static final Colour WHITE = new Colour(0xFF, 0xFF, 0xFF);

}

這種技術(shù)實(shí)現(xiàn)了RED, GREEN, BLUE 等可以象其他語言的枚舉類型一樣使用的常量。

他們可以用 '==' 操作符來比較。

但是這樣使用有一個(gè)缺陷:如果一個(gè)用戶用這樣的方法來創(chuàng)建顏色 BLACK new Colour(0,0,0)

那么這就是另外一個(gè)對(duì)象,'=='操作符就會(huì)產(chǎn)生錯(cuò)誤。她的 equal() 方法仍然有效。由于這個(gè)原因,這個(gè)技術(shù)的缺陷最好注明在文檔中,或者只在自己的包中使用。

8、編寫格式

代碼樣式

代碼應(yīng)該用 unix 的格式,而不是 windows 的(比如:回車變成回車+換行)

文檔化

必須用 javadoc 來為類生成文檔。不僅因?yàn)樗菢?biāo)準(zhǔn),這也是被各種 java 編譯器都認(rèn)可的方法。使用 @author 標(biāo)記是不被推薦的,因?yàn)榇a不應(yīng)該是被個(gè)人擁有的。

縮進(jìn)

縮進(jìn)應(yīng)該是每行2個(gè)空格. 不要在源文件中保存Tab字符. 在使用不同的源代碼管理工具時(shí)Tab字符將因?yàn)橛脩粼O(shè)置的不同而擴(kuò)展為不同的寬度.如果你使用 UltrEdit 作為你的 Java 源代碼編輯器的話,你可以通過如下操作來禁止保存Tab字符, 方法是通過 UltrEdit中先設(shè)定 Tab 使用的長度室2個(gè)空格,然后用 Format|Tabs to Spaces 菜單將 Tab 轉(zhuǎn)換為空格。

頁寬

頁寬應(yīng)該設(shè)置為80字符. 源代碼一般不會(huì)超過這個(gè)寬度, 并導(dǎo)致無法完整顯示, 但這一設(shè)置也可以靈活調(diào)整. 在任何情況下, 超長的語句應(yīng)該在一個(gè)逗號(hào)或者一個(gè)操作符后折行. 一條語句折行后, 應(yīng)該比原來的語句再縮進(jìn)2個(gè)字符.

{} 對(duì)

{} 中的語句應(yīng)該單獨(dú)作為一行. 例如, 下面的第1行是錯(cuò)誤的, 第2行是正確的:

if (i0) { i ++ }; // 錯(cuò)誤, { 和 } 在同一行

if (i0) {

i ++

}; // 正確, { 單獨(dú)作為一行

} 語句永遠(yuǎn)單獨(dú)作為一行.如果 } 語句應(yīng)該縮進(jìn)到與其相對(duì)應(yīng)的 { 那一行相對(duì)齊的位置。

括號(hào)

左括號(hào)和后一個(gè)字符之間不應(yīng)該出現(xiàn)空格, 同樣, 右括號(hào)和前一個(gè)字符之間也不應(yīng)該出現(xiàn)空格. 下面的例子說明括號(hào)和空格的錯(cuò)誤及正確使用:

CallProc( AParameter ); // 錯(cuò)誤

CallProc(AParameter); // 正確

不要在語句中使用無意義的括號(hào). 括號(hào)只應(yīng)該為達(dá)到某種目的而出現(xiàn)在源代碼中。下面的例子說明錯(cuò)誤和正確的用法:

if ((I) = 42) { // 錯(cuò)誤 - 括號(hào)毫無意義

if (I == 42) or (J == 42) then // 正確 - 的確需要括號(hào)

9、代碼編譯

1.編寫代碼時(shí)要注意隨時(shí)保存,并定期備份,防止由于斷電、硬盤損壞等原因造成代碼丟失。

2.同一項(xiàng)目組內(nèi),最好使用相同的編輯器,并使用相同的設(shè)置選項(xiàng)。

3.合理地設(shè)計(jì)軟件系統(tǒng)目錄,方便開發(fā)人員使用。

4.打開編譯器的所有告警開關(guān)對(duì)程序進(jìn)行編譯。

5.在同一項(xiàng)目組或產(chǎn)品組中,要統(tǒng)一編譯開關(guān)選項(xiàng)。

6.使用工具軟件(如Visual SourceSafe)對(duì)代碼版本進(jìn)行維護(hù)。如果大家有不明白的可以到安安DIY創(chuàng)作室留言。

10、可移植性

Borland Jbulider 不喜歡 synchronized 這個(gè)關(guān)鍵字,如果你的斷點(diǎn)設(shè)在這些關(guān)鍵字的作用域內(nèi)的話,調(diào)試的時(shí)候你會(huì)發(fā)現(xiàn)的斷點(diǎn)會(huì)到處亂跳,讓你不知所措。除非必須,盡量不要使用。

換行

如果需要換行的話,盡量用 println 來代替在字符串中使用\n。

你不要這樣:

System.out.print(Hello,world!\n);

要這樣:

System.out.println(Hello,world!);

或者你構(gòu)造一個(gè)帶換行符的字符串,至少要象這樣:

String newline = System.getProperty(line.separator);

System.out.println(Hello world + newline);

PrintStream

PrintStream 已經(jīng)被不贊成(deprecated)使用,用 PrintWrite 來代替它。

java io經(jīng)典代碼

package IO;

import java.io.*;

public class FileDirectoryDemo {

public static void main(String[] args) {

// 如果沒有指定參數(shù),則缺省為當(dāng)前目錄。

if (args.length == 0) {

args = new String[] { "." };

}

try {

// 新建指定目錄的File對(duì)象。

File currentPath = new File(args[0]);

// 在指定目錄新建temp目錄的File對(duì)象。

File tempPath = new File(currentPath, "temp");

// 用“tempPath”對(duì)象在指定目錄下創(chuàng)建temp目錄。

tempPath.mkdir();

// 在temp目錄下創(chuàng)建兩個(gè)文件。

File temp1 = new File(tempPath, "temp1.txt");

temp1.createNewFile();

File temp2 = new File(tempPath, "temp2.txt");

temp2.createNewFile();

// 遞歸顯示指定目錄的內(nèi)容。

System.out.println("顯示指定目錄的內(nèi)容");

listSubDir(currentPath);

// 更改文件名“temp1.txt”為“temp.txt”。

File temp1new = new File(tempPath, "temp.txt");

temp1.renameTo(temp1new);

// 遞歸顯示temp子目錄的內(nèi)容。

System.out.println("更改文件名后,顯示temp子目錄的內(nèi)容");

listSubDir(tempPath);

// 刪除文件“temp2.txt”。

temp2.delete();

// 遞歸顯示temp子目錄的內(nèi)容。

System.out.println("刪除文件后,顯示temp子目錄的內(nèi)容");

listSubDir(tempPath);

} catch (IOException e) {

System.err.println("IOException");

}

}

// 遞歸顯示指定目錄的內(nèi)容。

static void listSubDir(File currentPath) {

// 取得指定目錄的內(nèi)容列表。

String[] fileNames = currentPath.list();

try {

for (int i = 0; i fileNames.length; i++) {

File f = new File(currentPath.getPath(), fileNames[i]);

// 如果是目錄,則顯示目錄名后,遞歸調(diào)用,顯示子目錄的內(nèi)容。

if (f.isDirectory()) {

// 以規(guī)范的路徑格式顯示目錄。

System.out.println(f.getCanonicalPath());

// 遞歸調(diào)用,顯示子目錄。

listSubDir(f);

}

// 如果是文件,則顯示文件名,不包含路徑信息。

else {

System.out.println(f.getName());

}

}

} catch (IOException e) {

System.err.println("IOException");

}

}

}

package IO;

import java.io.*;

public class FileExample {

public FileExample() {

super();// 調(diào)用父類的構(gòu)造函數(shù)

}

public static void main(String[] args) {

try {

String outfile = "demoout.xml";

// 定義了一個(gè)變量, 用于標(biāo)識(shí)輸出文件

String infile = "demoin.xml";

// 定義了一個(gè)變量, 用于標(biāo)識(shí)輸入文件

DataOutputStream dt = new DataOutputStream(

new BufferedOutputStream(new FileOutputStream(outfile)));

/**

* 用FileOutputStream定義一個(gè)輸入流文件,

* 然后用BuferedOutputStream調(diào)用FileOutputStream對(duì)象生成一個(gè)緩沖輸出流

* 然后用DataOutputStream調(diào)用BuferedOutputStream對(duì)象生成數(shù)據(jù)格式化輸出流

*/

BufferedWriter NewFile = new BufferedWriter(new OutputStreamWriter(

dt, "gbk"));// 對(duì)中文的處理

DataInputStream rafFile1 = new DataInputStream(

new BufferedInputStream(new FileInputStream(infile)));

/**

*用FileInputStream定義一個(gè)輸入流文件,

* 然后用BuferedInputStream調(diào)用FileInputStream對(duì)象生成一個(gè)緩沖輸出流

* ,其后用DataInputStream中調(diào)用BuferedInputStream對(duì)象生成數(shù)據(jù)格式化輸出流

*/

BufferedReader rafFile = new BufferedReader(new InputStreamReader(

rafFile1, "gbk"));// 對(duì)中文的處理

String xmlcontent = "";

char tag = 0;// 文件用字符零結(jié)束

while (tag != (char) (-1)) {

xmlcontent = xmlcontent + tag + rafFile.readLine() + '\n';

}

NewFile.write(xmlcontent);

NewFile.flush();// 清空緩沖區(qū)

NewFile.close();

rafFile.close();

System.gc();// 強(qiáng)制立即回收垃圾,即釋放內(nèi)存。

} catch (NullPointerException exc) {

exc.printStackTrace();

} catch (java.lang.IndexOutOfBoundsException outb) {

System.out.println(outb.getMessage());

outb.printStackTrace();

} catch (FileNotFoundException fex) {

System.out.println("fex" + fex.getMessage());

} catch (IOException iex) {

System.out.println("iex" + iex.getMessage());

}

}

}

package IO;

import java.io.*;

public class FileRandomRW {

// 需要輸入的person數(shù)目。

public static int NUMBER = 3;

public static void main(String[] args) {

Persons[] people = new Persons[NUMBER];

people[0] = new Persons("張峰", 26, 2000, "N");

people[1] = new Persons("艷娜", 25, 50000, "Y");

people[2] = new Persons("李朋", 50, 7000, "F");

try {

DataOutputStream out = new DataOutputStream(new FileOutputStream(

"peoplerandom.dat"));

// 將人員數(shù)據(jù)保存至“peoplerandom.dat”二進(jìn)制文件中。

writeData(people, out);

// 關(guān)閉流。

out.close();

// 從二進(jìn)制文件“peoplerandom.dat”中逆序讀取數(shù)據(jù)。

RandomAccessFile inOut = new RandomAccessFile("peoplerandom.dat",

"rw");

Persons[] inPeople = readDataReverse(inOut);

// 輸出讀入的數(shù)據(jù)。

System.out.println("原始數(shù)據(jù):");

for (int i = 0; i inPeople.length; i++) {

System.out.println(inPeople[i]);

}

// 修改文件的第三條記錄。

inPeople[2].setSalary(4500);

// 將修改結(jié)果寫入文件。

inPeople[2].writeData(inOut, 3);

// 關(guān)閉流。

inOut.close();

// 從文件中讀入的第三條記錄,并輸出,以驗(yàn)證修改結(jié)果。

RandomAccessFile in = new RandomAccessFile("peoplerandom.dat", "r");

Persons in3People = new Persons();

// 隨機(jī)讀第三條記錄。

in3People.readData(in, 3);

// 關(guān)閉流。

in.close();

System.out.println("修改后的記錄");

System.out.println(in3People);

} catch (IOException exception) {

System.err.println("IOException");

}

}

// 將數(shù)據(jù)寫入輸出流。

static void writeData(Persons[] p, DataOutputStream out) throws IOException {

for (int i = 0; i p.length; i++) {

p[i].writeData(out);

}

}

// 將數(shù)據(jù)從輸入流中逆序讀出。

static Persons[] readDataReverse(RandomAccessFile in) throws IOException {

// 獲得記錄數(shù)目。

int record_num = (int) (in.length() / Persons.RECORD_LENGTH);

Persons[] p = new Persons[record_num];

// 逆序讀取。

for (int i = record_num - 1; i = 0; i--) {

p[i] = new Persons();

// 文件定位。

in.seek(i * Persons.RECORD_LENGTH);

p[i].readData(in, i + 1);

}

return p;

}

}

class Persons {

private String name;

private int age; // 4個(gè)字節(jié)

private double salary; // 8個(gè)字節(jié)

private String married;

public static final int NAME_LENGTH = 20; // 姓名長度

public static final int MARRIED_LENGTH = 2; // 婚否長度

public static final int RECORD_LENGTH = NAME_LENGTH * 2 + 4 + 8

+ MARRIED_LENGTH * 2;

public Persons() {

}

public Persons(String n, int a, double s) {

name = n;

age = a;

salary = s;

married = "F";

}

public Persons(String n, int a, double s, String m) {

name = n;

age = a;

salary = s;

married = m;

}

public String getName() {

return name;

}

public int getAge() {

return age;

}

public double getSalary() {

return salary;

}

public String getMarried() {

return married;

}

public String setName(String n) {

name = n;

return name;

}

public int setAge(int a) {

age = a;

return age;

}

public double setSalary(double s) {

salary = s;

return salary;

}

public String setMarried(String m) {

married = m;

return married;

}

// 設(shè)置輸出格式。

public String toString() {

return getClass().getName() + "[name=" + name + ",age=" + age

+ ",salary=" + salary + ",married=" + married + "]";

}

// 寫入一條固定長度的記錄,即一個(gè)人的數(shù)據(jù)到輸出流。

public void writeData(DataOutput out) throws IOException {

FixStringIO.writeFixString(name, NAME_LENGTH, out);

out.writeInt(age);

out.writeDouble(salary);

FixStringIO.writeFixString(married, MARRIED_LENGTH, out);

}

// 寫入一條固定長度的記錄到隨機(jī)讀取文件中。

private void writeData(RandomAccessFile out) throws IOException {

FixStringIO.writeFixString(name, NAME_LENGTH, out);

out.writeInt(age);

out.writeDouble(salary);

FixStringIO.writeFixString(married, MARRIED_LENGTH, out);

}

// 隨機(jī)寫入一條固定長度的記錄到輸出流的指定位置。

public void writeData(RandomAccessFile out, int n) throws IOException {

out.seek((n - 1) * RECORD_LENGTH);

writeData(out);

}

// 從輸入流隨機(jī)讀入一條記錄,即一個(gè)人的數(shù)據(jù)。

private void readData(RandomAccessFile in) throws IOException {

name = FixStringIO.readFixString(NAME_LENGTH, in);

age = in.readInt();

salary = in.readDouble();

married = FixStringIO.readFixString(MARRIED_LENGTH, in);

}

// 從輸入流隨機(jī)讀入指定位置的記錄。

public void readData(RandomAccessFile in, int n) throws IOException {

in.seek((n - 1) * RECORD_LENGTH);

readData(in);

}

}

// 對(duì)固定長度字符串從文件讀出、寫入文件

class FixStringIO {

// 讀取固定長度的Unicode字符串。

public static String readFixString(int size, DataInput in)

throws IOException {

StringBuffer b = new StringBuffer(size);

int i = 0;

boolean more = true;

while (more i size) {

char ch = in.readChar();

i++;

if (ch == 0) {

more = false;

} else {

b.append(ch);

}

}

// 跳過剩余的字節(jié)。

in.skipBytes(2 * (size - i));

return b.toString();

}

// 寫入固定長度的Unicode字符串。

public static void writeFixString(String s, int size, DataOutput out)

throws IOException {

int i;

for (i = 0; i size; i++) {

char ch = 0;

if (i s.length()) {

ch = s.charAt(i);

}

out.writeChar(ch);

}

}

}

package IO;

import java.io.*;

import java.util.*;

public class FileRW {

// 需要輸入的person數(shù)目。

public static int NUMBER = 3;

public static void main(String[] args) {

Person[] people = new Person[NUMBER];

// 暫時(shí)容納輸入數(shù)據(jù)的臨時(shí)字符串?dāng)?shù)組。

String[] field = new String[4];

// 初始化field數(shù)組。

for (int i = 0; i 4; i++) {

field[i] = "";

}

// IO操作必須捕獲IO異常。

try {

// 用于對(duì)field數(shù)組進(jìn)行增加控制。

int fieldcount = 0;

// 先使用System.in構(gòu)造InputStreamReader,再構(gòu)造BufferedReader。

BufferedReader stdin = new BufferedReader(new InputStreamReader(

System.in));

for (int i = 0; i NUMBER; i++) {

fieldcount = 0;

System.out.println("The number " + (i + 1) + " person");

System.out

.println("Enter name,age,salary,married(optional),please separate fields by ':'");

// 讀取一行。

String personstr = stdin.readLine();

// 設(shè)置分隔符。

StringTokenizer st = new StringTokenizer(personstr, ":");

// 判斷是否還有分隔符可用。

while (st.hasMoreTokens()) {

field[fieldcount] = st.nextToken();

fieldcount++;

}

// 如果輸入married,則field[3]不為空,調(diào)用具有四個(gè)參數(shù)的Person構(gòu)造函數(shù)。

if (field[3] != "") {

people[i] = new Person(field[0],

Integer.parseInt(field[1]), Double

.parseDouble(field[2]), field[3]);

// 置field[3]為空,以備下次輸入使用。

field[3] = "";

}

// 如果未輸入married,則field[3]為空,調(diào)用具有三個(gè)參數(shù)的Person構(gòu)造函數(shù)。

else {

people[i] = new Person(field[0],

Integer.parseInt(field[1]), Double

.parseDouble(field[2]));

}

}

// 將輸入的數(shù)據(jù)保存至“people.dat”文本文件中。

PrintWriter out = new PrintWriter(new BufferedWriter(

new FileWriter("people.dat")));

writeData(people, out);

// 關(guān)閉流。

out.close();

// 從文件“people.dat”讀取數(shù)據(jù)。

BufferedReader in = new BufferedReader(new FileReader("people.dat"));

Person[] inPeople = readData(in);

// 關(guān)閉流。

in.close();

// 輸出從文件中讀入的數(shù)據(jù)。

for (int i = 0; i inPeople.length; i++) {

System.out.println(inPeople[i]);

}

} catch (IOException exception) {

System.err.println("IOException");

}

}

// 將所有數(shù)據(jù)寫入輸出流。

static void writeData(Person[] p, PrintWriter out) throws IOException {

// 寫入記錄條數(shù),即人數(shù)。

out.println(p.length);

for (int i = 0; i p.length; i++) {

p[i].writeData(out);

}

}

// 將所有數(shù)據(jù)從輸入流中讀出。

static Person[] readData(BufferedReader in) throws IOException {

// 獲取記錄條數(shù),即人數(shù)。

int n = Integer.parseInt(in.readLine());

Person[] p = new Person[n];

for (int i = 0; i n; i++) {

p[i] = new Person();

p[i].readData(in);

}

return p;

}

}

class Person {

private String name;

private int age;

private double salary;

private String married;

public Person() {

}

public Person(String n, int a, double s) {

name = n;

age = a;

salary = s;

married = "F";

}

public Person(String n, int a, double s, String m) {

name = n;

age = a;

salary = s;

married = m;

}

public String getName() {

return name;

}

public int getAge() {

return age;

}

public double getSalary() {

return salary;

}

public String getMarried() {

return married;

}

// 設(shè)置輸出格式。

public String toString() {

return getClass().getName() + "[name=" + name + ",age=" + age

+ ",salary=" + salary + ",married=" + married + "]";

}

// 寫入一條記錄,即一個(gè)人的數(shù)據(jù)到輸出流。

public void writeData(PrintWriter out) throws IOException {

// 格式化輸出。

out.println(name + ":" + age + ":" + salary + ":" + married);

}

// 從輸入流讀入一條記錄,即一個(gè)人的數(shù)據(jù)。

public void readData(BufferedReader in) throws IOException {

String s = in.readLine();

StringTokenizer t = new StringTokenizer(s, ":");

name = t.nextToken();

age = Integer.parseInt(t.nextToken());

salary = Double.parseDouble(t.nextToken());

married = t.nextToken();

}

}

package IO;

import java.io.IOException;

public class FileStdRead {

public static void main(String[] args) throws IOException {

int b = 0;

char c = ' ';

System.out.println("請(qǐng)輸入:");

while (c != 'q') {

int a = System.in.read();

c = (char) a;

b++;

System.out.println((char) a);

}

System.err.print("counted\t" + b + "\ttotalbytes.");

}

}

//讀取輸入的數(shù)據(jù),直到數(shù)據(jù)中有Q這個(gè)字母然

package IO;

import java.io.*;

public class IOStreamExample {

public static void main(String[] args) throws IOException {

// 1. 讀入一行數(shù)據(jù):

BufferedReader in = new BufferedReader(new FileReader(

"FileStdRead.java"));

String s, s2 = new String();

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

s2 += s + "\n";

}

in.close();

BufferedReader stdin = new BufferedReader(new InputStreamReader(

System.in));

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

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

// 2. 從內(nèi)存中讀入

StringReader in2 = new StringReader(s2);

int c;

while ((c = in2.read()) != -1) {

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

}

// 3. 格式化內(nèi)存輸入

try {

DataInputStream in3 = new DataInputStream(new ByteArrayInputStream(

s2.getBytes()));

while (true) {

System.out.print((char) in3.readByte());

}

} catch (EOFException e) {

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

}

// 4. 文件輸入

try {

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

PrintWriter out1 = new PrintWriter(new BufferedWriter(

new FileWriter("IODemo.out")));

int lineCount = 1;

while ((s = in4.readLine()) != null) {

out1.println(lineCount++ + ": " + s);

}

out1.close();

} catch (EOFException e) {

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

}

// 5. 接收和保存數(shù)據(jù)

try {

DataOutputStream out2 = new DataOutputStream(

new BufferedOutputStream(new FileOutputStream("Data.txt")));

out2.writeDouble(3.14159);

out2.writeUTF("That was pi");

out2.writeDouble(1.41413);

out2.writeUTF("Square root of 2");

out2.close();

DataInputStream in5 = new DataInputStream(new BufferedInputStream(

new FileInputStream("Data.txt")));

System.out.println(in5.readDouble());

System.out.println(in5.readUTF());

System.out.println(in5.readDouble());

System.out.println(in5.readUTF());

} catch (EOFException e) {

throw new RuntimeException(e);

}

// 6. 隨機(jī)讀取文件內(nèi)容

RandomAccessFile rf = new RandomAccessFile("rtest.dat", "rw");

for (int i = 0; i 10; i++) {

rf.writeDouble(i * 1.414);

}

rf.close();

rf = new RandomAccessFile("rtest.dat", "rw");

rf.seek(5 * 8);

rf.writeDouble(47.0001);

rf.close();

rf = new RandomAccessFile("rtest.dat", "r");

for (int i = 0; i 10; i++) {

System.out.println("Value " + i + ": " + rf.readDouble());

}

rf.close();

}

}

package IO;

import java.io.*;

/**

* p

* Title: JAVA進(jìn)階訣竅

* /p

*

* @author 張峰

* @version 1.0

*/

public class MakeDirectoriesExample {

private static void fileattrib(File f) {

System.out.println("絕對(duì)路徑: " + f.getAbsolutePath() + "\n 可讀屬性: "

+ f.canRead() + "\n 可定屬性: " + f.canWrite() + "\n 文件名: "

+ f.getName() + "\n 父目錄: " + f.getParent() + "\n 當(dāng)前路徑: "

+ f.getPath() + "\n 文件長度: " + f.length() + "\n 最后更新日期: "

+ f.lastModified());

if (f.isFile()) {

System.out.println("輸入的是一個(gè)文件");

} else if (f.isDirectory()) {

System.out.println("輸入的是一個(gè)目錄");

}

}

public static void main(String[] args) {

if (args.length 1) {

args = new String[3];

}

args[0] = "d";

args[1] = "test1.txt";

args[2] = "test2.txt";

File old = new File(args[1]), rname = new File(args[2]);

old.renameTo(rname);

fileattrib(old);

fileattrib(rname);

int count = 0;

boolean del = false;

if (args[0].equals("d")) {

count++;

del = true;

}

count--;

while (++count args.length) {

File f = new File(args[count]);

if (f.exists()) {

System.out.println(f + " 文件己經(jīng)存在");

if (del) {

System.out.println("刪除文件" + f);

f.delete();

}

} else { // 如果文件不存在

if (!del) {

f.mkdirs();

System.out.println("創(chuàng)建文件: " + f);

}

}

fileattrib(f);

}

}

}

JAVA 文件IO操作練習(xí),需要完整代碼解答

描述較為簡(jiǎn)略,如有疑問可追答

public static void main(String[] s){

move(new File("源文件夾"), new File("需要移動(dòng)到的文件夾"));

}

/**

* 將文件(夾)移動(dòng)到令一個(gè)文件夾

*/

public static void move(File resFile, File objFolderFile, boolean flag)

throws IOException {

copy(resFile, objFolderFile, flag);

delete(resFile);

}

/**

* 復(fù)制文件(夾)到一個(gè)目標(biāo)文件夾

*

* @param resFile

* 源文件(夾)

* @param objFolderFile

* 目標(biāo)文件夾

*/

public static void copy(File resFile, File objFolderFile, boolean flag)

throws IOException {

if (!resFile.exists())

return;

if (!objFolderFile.exists())

objFolderFile.mkdirs();

if (resFile.isFile()) {

File objFile = new File(objFolderFile.getPath() + File.separator

+ resFile.getName());

// 復(fù)制文件到目標(biāo)地

InputStream ins = new FileInputStream(resFile);

FileOutputStream outs = new FileOutputStream(objFile);

byte[] buffer = new byte[1024 * 512];

int length;

while ((length = ins.read(buffer)) != -1) {

outs.write(buffer, 0, length);

}

ins.close();

outs.flush();

outs.close();

} else {

String objFolder;

if (flag)

objFolder = objFolderFile.getPath();

else

objFolder = objFolderFile.getPath() + File.separator

+ resFile.getName();

File _objFolderFile = new File(objFolder);

_objFolderFile.mkdirs();

for (File sf : resFile.listFiles()) {

copy(sf, new File(objFolder), false);

}

}

}

/**

* 刪除文件(夾)

*/

public static void delete(File file) {

if (file == null)

return;

if (!file.exists())

return;

if (file.isFile()) {

file.delete();

} else {

for (File f : file.listFiles()) {

delete(f);

}

file.delete();

}

}

初學(xué)java,請(qǐng)教java的io流的一段代碼

read()方法會(huì)返回一個(gè)整形類型的數(shù),-1代表讀完數(shù)據(jù),不是-1代表沒讀完

by=bufis.read() //后面不看先

把read()方法的返回值賦給by。

然后再判斷這個(gè)by是不是為-1

其實(shí)就是簡(jiǎn)寫而已。。。

名稱欄目:java快速io代碼模版 java io源碼
當(dāng)前路徑:http://www.chinadenli.net/article0/doojeoo.html

成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供微信公眾號(hào)網(wǎng)站設(shè)計(jì)公司網(wǎng)站制作移動(dòng)網(wǎng)站建設(shè)品牌網(wǎng)站設(shè)計(jì)企業(yè)建站

廣告

聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如需處理請(qǐng)聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來源: 創(chuàng)新互聯(lián)

外貿(mào)網(wǎng)站建設(shè)