资讯

精准传达 • 有效沟通

从品牌网站建设到网络营销策划,从策略到执行的一站式服务

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

java 代码关于IO 的,高手帮忙解答 这个代码实现什么功能??

in.read()是读取一个数据字节的意思,返回的是0~255的int型数据,在你这个代码里面可以任意输入,

创新互联主营嘉荫网站建设的网络公司,主营网站建设方案,成都App制作,嘉荫h5微信平台小程序开发搭建,嘉荫网站营销推广欢迎嘉荫等地区企业咨询

(char)i则是将刚刚读取的int型字节强制转换成char型的,而且你的代码那个构造函数有错,就是打错了

下面是你的代码我把那个小错给你改了,还有你把 System.out.print(c);换成 System.out.println(c);就会更好的理解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软件开发的代码规范

1、组织与风格

(1).关键词和操作符之间加适当的空格。

(2).相对独立的程序块与块之间加空行

(3).较长的语句、表达式等要分成多行书写。

(4).划分出的新行要进行适应的缩进,使排版整齐,语句可读。

(5).长表达式要在低优先级操作符处划分新行,操作符放在新行之首。

(6).循环、判断等语句中若有较长的表达式或语句,则要进行适应的划分。

(7).若函数或过程中的参数较长,则要进行适当的划分。

(8).不允许把多个短语句写在一行中,即一行只写一条语句。

(9).函数或过程的开始、结构的定义及循环、判断等语句中的代码都要采用缩进风格。

注:如果大家有兴趣可以到安安DIY创作室博客,有相关说明性的文章和解释。

2、注解

Java 的语法与 C++ 及为相似,那么,你知道 Java 的注释有几种吗?是两种?

// 注释一行

/* ...... */ 注释若干行

不完全对,除了以上两种之外,还有第三种,文档注释:

/** ...... */ 注释若干行,并写入 javadoc 文档

注释要简单明了。

String userName = null; //用户名

边写代码边注释,修改代码同时修改相应的注释,以保证注释与代码的一致性。

在必要的地方注释,注释量要适中。注释的内容要清楚、明了,含义准确,防止注释二义性。

保持注释与其描述的代码相邻,即注释的就近原则。

对代码的注释应放在其上方相邻位置,不可放在下面。对数据结构的注释应放在其上方相邻位置,不可放在下面;对结构中的每个域的注释应放在此域的右方;

同一结构中不同域的注释要对齐。

变量、常量的注释应放在其上方相邻位置或右方。

全局变量要有较详细的注释,包括对其功能、取值范围、哪些函数或过程存取它以及存取时注意事项等的说明。

在每个源文件的头部要有必要的注释信息,包括:文件名;版本号;作者;生成日期;模块功能描述(如功能、主要算法、内部各部分之间的关系、该文件与其它文件关系等);主要函数或过程清单及本文件历史修改记录等。

/**

* 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

**/

在每个函数或过程的前面要有必要的注释信息,包括:函数或过程名称;功能描述;输入、输出及返回值说明;调用关系及被调用关系说明等

/**

* Description :checkout 提款

* @param Hashtable cart info

* @param OrderBean order info

* @return String

*/

public String checkout(Hashtable htCart,

OrderBean orderBean)

throws Exception{

}

javadoc注释标签语法

@author 对类的说明 标明开发该类模块的作者

@version 对类的说明 标明该类模块的版本

@see 对类、属性、方法的说明 参考转向,也就是相关主题

@param 对方法的说明 对方法中某参数的说明

@return 对方法的说明 对方法返回值的说明

@exception 对方法的说明 对方法可能抛出的异常进行说明

3、命名规范

定义这个规范的目的是让项目中所有的文档都看起来像一个人写的,增加可读性,减少项目组中因为换人而带来的损失。(这些规范并不是一定要绝对遵守,但是一定要让程序有良好的可读性)较短的单词可通过去掉元音形成缩写;要不然最后自己写的代码自己都看不懂了,那可不行。

较长的单词可取单词的头几发符的优先级,并用括号明确表达式的操作顺序,避免使用默认优先级。

使用匈牙利表示法

Package 的命名

Package 的名字应该都是由一个小写单词组成。

package com.neu.util

Class 的命名

Class 的名字必须由大写字母开头而其他字母都小写的单词组成,对于所有标识符,其中包含的所有单词都应紧靠在一起,而且大写中间单词的首字母。

public class ThisAClassName{}

Class 变量的命名

变量的名字必须用一个小写字母开头。后面的单词用大写字母开头

userName , thisAClassMethod

Static Final 变量的命名

static Final 变量的名字应该都大写,并且指出完整含义。

/**

*DBConfig PATH

**/

public static final String

DB_CONFIG_FILE_PATH =com.neu.etrain.dbconfig;

参数的命名

参数的名字必须和变量的命名规范一致。

数组的命名

数组应该总是用下面的方式来命名:

byte[] buffer;

而不是:

byte buffer[];

方法的参数

使用有意义的参数命名,如果可能的话,使用和要赋值的字段一样的名字:

SetCounter(int size){

this.size = size;

}

4、文件样式

所有的 Java(*.java) 文件都必须遵守如下的样式规则:

版权信息

版权信息必须在 java 文件的开头,比如:

/*

* Copyright ? 2000 Shanghai XXX Co. Ltd.

* All right reserved.

*/

其他不需要出现在 javadoc 的信息也可以包含在这里。

Package/Imports

package 行要在 import 行之前,import 中标准的包名要在本地的包名之前,而且按照字母

顺序排列。如果 import 行中包含了同一个包中的不同子目录,则应该用 * 来处理。

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 定义的成

员变量如果名字含义明确的话,可以没有注释。

存取方法

接下来是类变量的存取的方法。它只是简单的用来将类的变量赋值获取值的话,可以简单的

写在一行上。

/**

* 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; }

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

构造函数

接下来是构造函数,它应该用递增的方式写(比如:参数多的写在后面)。

访问类型 (public, private 等.) 和 任何 static, final 或 synchronized 应该在一行

中,并且方法和参数另写一行,这样可以使方法和参数更易读。

public

CounterSet(int size){

this.size = size;

}

克隆方法

如果这个类是可以被克隆的,那么下一步就是 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 方法

无论如何,每一个类都应该定义 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[]) 方法已经定义了, 那么它应该写在类的底部.

5、代码可读性

避免使用不易理解的数字,用有意义的标识来替代。

不要使用难懂的技巧性很高的语句。

源程序中关系较为紧密的代码应尽可能相邻。

6、代码性能

在写代码的时候,从头至尾都应该考虑性能问题。这不是说时间都应该浪费在优化代码上,而是我们时刻应该提醒自己要注意代码的效率。比如:如果没有时间来实现一个高效的算法,那么我们应该在文档中记录下来,以便在以后有空的时候再来实现她。

不是所有的人都同意在写代码的时候应该优化性能这个观点的,他们认为性能优化的问题应该在项目的后期再去考虑,也就是在程序的轮廓已经实现了以后。

不必要的对象构造

不要在循环中构造和释放对象

使用 StringBuffer 对象

在处理 String 的时候要尽量使用 StringBuffer 类,StringBuffer 类是构成 String 类的基础。

String 类将 StringBuffer 类封装了起来,(以花费更多时间为代价)为开发人员提供了一个安全的接口。当我们在构造字符串的时候,我们应该用 StringBuffer 来实现大部分的工作,当工作完成后将 StringBuffer 对象再转换为需要的 String 对象。比如:如果有一个字符串必须不断地在其后添加许多字符来完成构造,那么我们应该使用StringBuffer 对象和她的 append() 方法。如果我们用 String 对象代替StringBuffer 对象的话,会花费许多不必要的创建和释放对象的 CPU 时间。大家可以来安安DIY创作室一起讨论。

避免太多的使用 synchronized 关键字避免不必要的使用关键字 synchronized,应该在必要的时候再使用她,这是一个避免死锁的好方法。

7、编程技巧

byte 数组转换到 characters

为了将 byte 数组转换到 characters,你可以这么做:

Hello world!.getBytes();

Utility 类

Utility 类(仅仅提供方法的类)应该被申明为抽象的来防止被继承或被初始化。

初始化

下面的代码是一种很好的初始化数组的方法:

objectArguments = new Object[] { arguments };

枚举类型

JAVA 对枚举的支持不好,但是下面的代码是一种很有用的模板:

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);

}

这种技术实现了RED, GREEN, BLUE 等可以象其他语言的枚举类型一样使用的常量。

他们可以用 '==' 操作符来比较。

但是这样使用有一个缺陷:如果一个用户用这样的方法来创建颜色 BLACK new Colour(0,0,0)

那么这就是另外一个对象,'=='操作符就会产生错误。她的 equal() 方法仍然有效。由于这个原因,这个技术的缺陷最好注明在文档中,或者只在自己的包中使用。

8、编写格式

代码样式

代码应该用 unix 的格式,而不是 windows 的(比如:回车变成回车+换行)

文档化

必须用 javadoc 来为类生成文档。不仅因为它是标准,这也是被各种 java 编译器都认可的方法。使用 @author 标记是不被推荐的,因为代码不应该是被个人拥有的。

缩进

缩进应该是每行2个空格. 不要在源文件中保存Tab字符. 在使用不同的源代码管理工具时Tab字符将因为用户设置的不同而扩展为不同的宽度.如果你使用 UltrEdit 作为你的 Java 源代码编辑器的话,你可以通过如下操作来禁止保存Tab字符, 方法是通过 UltrEdit中先设定 Tab 使用的长度室2个空格,然后用 Format|Tabs to Spaces 菜单将 Tab 转换为空格。

页宽

页宽应该设置为80字符. 源代码一般不会超过这个宽度, 并导致无法完整显示, 但这一设置也可以灵活调整. 在任何情况下, 超长的语句应该在一个逗号或者一个操作符后折行. 一条语句折行后, 应该比原来的语句再缩进2个字符.

{} 对

{} 中的语句应该单独作为一行. 例如, 下面的第1行是错误的, 第2行是正确的:

if (i0) { i ++ }; // 错误, { 和 } 在同一行

if (i0) {

i ++

}; // 正确, { 单独作为一行

} 语句永远单独作为一行.如果 } 语句应该缩进到与其相对应的 { 那一行相对齐的位置。

括号

左括号和后一个字符之间不应该出现空格, 同样, 右括号和前一个字符之间也不应该出现空格. 下面的例子说明括号和空格的错误及正确使用:

CallProc( AParameter ); // 错误

CallProc(AParameter); // 正确

不要在语句中使用无意义的括号. 括号只应该为达到某种目的而出现在源代码中。下面的例子说明错误和正确的用法:

if ((I) = 42) { // 错误 - 括号毫无意义

if (I == 42) or (J == 42) then // 正确 - 的确需要括号

9、代码编译

1.编写代码时要注意随时保存,并定期备份,防止由于断电、硬盘损坏等原因造成代码丢失。

2.同一项目组内,最好使用相同的编辑器,并使用相同的设置选项。

3.合理地设计软件系统目录,方便开发人员使用。

4.打开编译器的所有告警开关对程序进行编译。

5.在同一项目组或产品组中,要统一编译开关选项。

6.使用工具软件(如Visual SourceSafe)对代码版本进行维护。如果大家有不明白的可以到安安DIY创作室留言。

10、可移植性

Borland Jbulider 不喜欢 synchronized 这个关键字,如果你的断点设在这些关键字的作用域内的话,调试的时候你会发现的断点会到处乱跳,让你不知所措。除非必须,尽量不要使用。

换行

如果需要换行的话,尽量用 println 来代替在字符串中使用\n。

你不要这样:

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

要这样:

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

或者你构造一个带换行符的字符串,至少要象这样:

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

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

PrintStream

PrintStream 已经被不赞成(deprecated)使用,用 PrintWrite 来代替它。

java io经典代码

package IO;

import java.io.*;

public class FileDirectoryDemo {

public static void main(String[] args) {

// 如果没有指定参数,则缺省为当前目录。

if (args.length == 0) {

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

}

try {

// 新建指定目录的File对象。

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

// 在指定目录新建temp目录的File对象。

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

// 用“tempPath”对象在指定目录下创建temp目录。

tempPath.mkdir();

// 在temp目录下创建两个文件。

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

temp1.createNewFile();

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

temp2.createNewFile();

// 递归显示指定目录的内容。

System.out.println("显示指定目录的内容");

listSubDir(currentPath);

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

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

temp1.renameTo(temp1new);

// 递归显示temp子目录的内容。

System.out.println("更改文件名后,显示temp子目录的内容");

listSubDir(tempPath);

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

temp2.delete();

// 递归显示temp子目录的内容。

System.out.println("删除文件后,显示temp子目录的内容");

listSubDir(tempPath);

} catch (IOException e) {

System.err.println("IOException");

}

}

// 递归显示指定目录的内容。

static void listSubDir(File currentPath) {

// 取得指定目录的内容列表。

String[] fileNames = currentPath.list();

try {

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

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

// 如果是目录,则显示目录名后,递归调用,显示子目录的内容。

if (f.isDirectory()) {

// 以规范的路径格式显示目录。

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

// 递归调用,显示子目录。

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();// 调用父类的构造函数

}

public static void main(String[] args) {

try {

String outfile = "demoout.xml";

// 定义了一个变量, 用于标识输出文件

String infile = "demoin.xml";

// 定义了一个变量, 用于标识输入文件

DataOutputStream dt = new DataOutputStream(

new BufferedOutputStream(new FileOutputStream(outfile)));

/**

* 用FileOutputStream定义一个输入流文件,

* 然后用BuferedOutputStream调用FileOutputStream对象生成一个缓冲输出流

* 然后用DataOutputStream调用BuferedOutputStream对象生成数据格式化输出流

*/

BufferedWriter NewFile = new BufferedWriter(new OutputStreamWriter(

dt, "gbk"));// 对中文的处理

DataInputStream rafFile1 = new DataInputStream(

new BufferedInputStream(new FileInputStream(infile)));

/**

*用FileInputStream定义一个输入流文件,

* 然后用BuferedInputStream调用FileInputStream对象生成一个缓冲输出流

* ,其后用DataInputStream中调用BuferedInputStream对象生成数据格式化输出流

*/

BufferedReader rafFile = new BufferedReader(new InputStreamReader(

rafFile1, "gbk"));// 对中文的处理

String xmlcontent = "";

char tag = 0;// 文件用字符零结束

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

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

}

NewFile.write(xmlcontent);

NewFile.flush();// 清空缓冲区

NewFile.close();

rafFile.close();

System.gc();// 强制立即回收垃圾,即释放内存。

} 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数目。

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"));

// 将人员数据保存至“peoplerandom.dat”二进制文件中。

writeData(people, out);

// 关闭流。

out.close();

// 从二进制文件“peoplerandom.dat”中逆序读取数据。

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

"rw");

Persons[] inPeople = readDataReverse(inOut);

// 输出读入的数据。

System.out.println("原始数据:");

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

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

}

// 修改文件的第三条记录。

inPeople[2].setSalary(4500);

// 将修改结果写入文件。

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

// 关闭流。

inOut.close();

// 从文件中读入的第三条记录,并输出,以验证修改结果。

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

Persons in3People = new Persons();

// 随机读第三条记录。

in3People.readData(in, 3);

// 关闭流。

in.close();

System.out.println("修改后的记录");

System.out.println(in3People);

} catch (IOException exception) {

System.err.println("IOException");

}

}

// 将数据写入输出流。

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

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

p[i].writeData(out);

}

}

// 将数据从输入流中逆序读出。

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

// 获得记录数目。

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个字节

private double salary; // 8个字节

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;

}

// 设置输出格式。

public String toString() {

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

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

}

// 写入一条固定长度的记录,即一个人的数据到输出流。

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);

}

// 写入一条固定长度的记录到随机读取文件中。

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);

}

// 随机写入一条固定长度的记录到输出流的指定位置。

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

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

writeData(out);

}

// 从输入流随机读入一条记录,即一个人的数据。

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);

}

// 从输入流随机读入指定位置的记录。

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

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

readData(in);

}

}

// 对固定长度字符串从文件读出、写入文件

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);

}

}

// 跳过剩余的字节。

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数目。

public static int NUMBER = 3;

public static void main(String[] args) {

Person[] people = new Person[NUMBER];

// 暂时容纳输入数据的临时字符串数组。

String[] field = new String[4];

// 初始化field数组。

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

field[i] = "";

}

// IO操作必须捕获IO异常。

try {

// 用于对field数组进行增加控制。

int fieldcount = 0;

// 先使用System.in构造InputStreamReader,再构造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();

// 设置分隔符。

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

// 判断是否还有分隔符可用。

while (st.hasMoreTokens()) {

field[fieldcount] = st.nextToken();

fieldcount++;

}

// 如果输入married,则field[3]不为空,调用具有四个参数的Person构造函数。

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]为空,调用具有三个参数的Person构造函数。

else {

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

Integer.parseInt(field[1]), Double

.parseDouble(field[2]));

}

}

// 将输入的数据保存至“people.dat”文本文件中。

PrintWriter out = new PrintWriter(new BufferedWriter(

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

writeData(people, out);

// 关闭流。

out.close();

// 从文件“people.dat”读取数据。

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

Person[] inPeople = readData(in);

// 关闭流。

in.close();

// 输出从文件中读入的数据。

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

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

}

} catch (IOException exception) {

System.err.println("IOException");

}

}

// 将所有数据写入输出流。

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

// 写入记录条数,即人数。

out.println(p.length);

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

p[i].writeData(out);

}

}

// 将所有数据从输入流中读出。

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

// 获取记录条数,即人数。

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;

}

// 设置输出格式。

public String toString() {

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

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

}

// 写入一条记录,即一个人的数据到输出流。

public void writeData(PrintWriter out) throws IOException {

// 格式化输出。

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

}

// 从输入流读入一条记录,即一个人的数据。

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("请输入:");

while (c != 'q') {

int a = System.in.read();

c = (char) a;

b++;

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

}

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

}

}

//读取输入的数据,直到数据中有Q这个字母然

package IO;

import java.io.*;

public class IOStreamExample {

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

// 1. 读入一行数据:

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. 从内存中读入

StringReader in2 = new StringReader(s2);

int c;

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

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

}

// 3. 格式化内存输入

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. 接收和保存数据

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. 随机读取文件内容

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进阶诀窍

* /p

*

* @author 张峰

* @version 1.0

*/

public class MakeDirectoriesExample {

private static void fileattrib(File f) {

System.out.println("绝对路径: " + f.getAbsolutePath() + "\n 可读属性: "

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

+ f.getName() + "\n 父目录: " + f.getParent() + "\n 当前路径: "

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

+ f.lastModified());

if (f.isFile()) {

System.out.println("输入的是一个文件");

} else if (f.isDirectory()) {

System.out.println("输入的是一个目录");

}

}

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 + " 文件己经存在");

if (del) {

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

f.delete();

}

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

if (!del) {

f.mkdirs();

System.out.println("创建文件: " + f);

}

}

fileattrib(f);

}

}

}

JAVA 文件IO操作练习,需要完整代码解答

描述较为简略,如有疑问可追答

public static void main(String[] s){

move(new File("源文件夹"), new File("需要移动到的文件夹"));

}

/**

* 将文件(夹)移动到令一个文件夹

*/

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

throws IOException {

copy(resFile, objFolderFile, flag);

delete(resFile);

}

/**

* 复制文件(夹)到一个目标文件夹

*

* @param resFile

* 源文件(夹)

* @param objFolderFile

* 目标文件夹

*/

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());

// 复制文件到目标地

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();

}

}

初学java,请教java的io流的一段代码

read()方法会返回一个整形类型的数,-1代表读完数据,不是-1代表没读完

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

把read()方法的返回值赋给by。

然后再判断这个by是不是为-1

其实就是简写而已。。。


新闻名称:java快速io代码模版 java io源码
文章转载:http://cdkjz.cn/article/doojeoo.html
多年建站经验

多一份参考,总有益处

联系快上网,免费获得专属《策划方案》及报价

咨询相关问题或预约面谈,可以通过以下方式与我们联系

大客户专线   成都:13518219792   座机:028-86922220