目录

第一章:Java IO编程

1.1  文件操作类:File

范例1-1:文件基本操作。任意给定一个文件路径,如果文件不存在则创建一个新的文件,如果文件存在则将文件删除。

范例1-2:创建带路径的文件。

范例1-3:取得文件或目录的信息。

范例1-4:列出目录信息。

范例1-5:列出指定目录下的所有文件及子目录信息。在每一个目录中有可能还会存在其他子目录,并且还可能有更深层次的子目录,所以为了可以列出所有的内容,应该判断每一个给定的路径是否是目录。如果是目录则应该继续列出,这样的操作最好使用递归的方式完成。

正在上传…重新上传取消1.2  字节流与字符流

范例1-6:自动执行close()操作。

范例1-7:文件内容的输出。

范例1-8:文件追加。

范例1-9:采用单个字节的方式输出(此处可以利用循环操作输出全部字节数组中的数据)。

范例1-10:输出部分字节数组内容(设置数组的开始索引和长度)。

范例1-11:数据读取操作。

范例1-12:采用while循环实现输入流操作。

范例1-13:利用do…while实现数据读取。

范例1-14:使用Writer类实现内容输出

范例1-15:使用Reader读取数据。

范例1-16:强制清空字符流缓冲区。

1.3  转换流

范例1-17:实现输出流转换。

1.4  案例:文件复制

范例1-18:实现文件复制操作。

正在上传…重新上传取消1.5  字符编码

范例1-19:取得当前系统中的环境属性中的文件编码。

范例1-20:程序出现乱码。

正在上传…重新上传取消1.6  内存流

范例1-21:实现一个小写字母转大写字母的操作。

范例1-22:实现文件的合并读取。

1.7  打印流

范例1-23:定义打印流工具类

范例1-24:使用PrintStream类实现输出。

范例1-25:格式化输出。

范例1-26:格式化字符串。

1.8  System类对IO的支持

范例1-27:错误输出。

范例1-28:利用OutputStream实现屏幕输出。

范例1-29:消费型函数式接口与方法引用。

范例1-30:实现键盘的数据输入。

范例1-31:改进输入操作设计。

正在上传…重新上传取消1.9  字符缓冲流:BufferedReader

范例1-32:键盘数据输入的标准格式。

范例1-33:判断输入内容。

范例1-34:读取文件。

正在上传…重新上传取消1.10  扫描流:Scanner

范例1-35:利用Scanner实现键盘数据输入。

范例1-36:输入一个数字——double。

范例1-37:正则验证。

范例1-38:读取文件。

正在上传…重新上传取消1.11  对象序列化

范例1-39:定义一个可以被序列化对象的类。

范例1-40:实现序列化对象操作——ObjectOutputStream。

范例1-41:实现反序列化操作——ObjectInputStream。

范例1-42:定义不需要序列化的属性。


第一章:Java IO编程

1.1  文件操作类:File

范例1-1:文件基本操作。任意给定一个文件路径,如果文件不存在则创建一个新的文件,如果文件存在则将文件删除。

package com.yootk.demo;

import java.io.File;

public class TestDemo {

public static void main(String[] args) throws Exception { // 此处直接抛出

File file = new File("d:\\test.txt"); // 设置文件的路径

if (file.exists()) { // 判断文件是否存在

file.delete(); // 删除文件

} else { // 文件不存在

System.out.println(file.createNewFile()); // 创建新文件

}

}

}

范例1-2:创建带路径的文件。

如果给定的路径为根路径,则文件可以直接利用createNewFile()方法进行创建;如果要创建的文件存在目录,那么将无法进行创建。所以合理的做法应该是在创建文件前判断父路径(getParent()取得父路径)是否存在,如果不存在则应该先创建目录(mkdirs()创建多级目录),再创建文件。包含路径的文件创建如图1-2所示。

package com.yootk.demo;

import java.io.File;

public class TestDemo {

public static void main(String[] args) throws Exception { // 此处直接抛出

File file = new File("d:" + File.separator + "demo" + File.separator

+ "hello" + File.separator + "yootk" + File.separator

+ "test.txt"); // 设置文件的路径

if (!file.getParentFile().exists()) { // 现在父路径不存在

file.getParentFile().mkdirs(); // 创建父路径

}

System.out.println(file.createNewFile()); // 创建新文件

}

}

范例1-3:取得文件或目录的信息。

package com.yootk.demo;

import java.io.File;

import java.math.BigDecimal;

import java.text.SimpleDateFormat;

import java.util.Date;

public class TestDemo {

public static void main(String[] args) throws Exception {  // 此处直接抛出

File file = new File("d:" + File.separator + "my.jpg"); // 设置文件的路径

if (file.exists()) {

System.out.println("是否是文件:" + (file.isFile()));

System.out.println("是否是目录:" + (file.isDirectory()));

// 文件大小是按照字节单位返回的数字,所以需要将字节单元转换为兆(M)的单元

// 但是考虑到小数点问题,所以使用BigDecimal处理

System.out.println("文件大小:"

+ (new BigDecimal((double) file.length() / 1024 / 1024)

.divide(new BigDecimal(1), 2,

BigDecimal.ROUND_HALF_UP)) + "M");

// 返回的日期是以long的形式返回,可以利用SimpleDateFormat进行格式化操作

System.out.println("上次修改时间:"

+ new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")

.format(new Date(file.lastModified())));

}

}

}

范例1-4:列出目录信息。

package com.yootk.demo;

import java.io.File;

public class TestDemo {

public static void main(String[] args) throws Exception { // 此处直接抛出

File file = new File("c:" + File.separator);

if (file.isDirectory()) { // 判断当前路径是否为目录

File result [] = file.listFiles() ;

for (int x = 0; x < result.length; x++) {

System.out.println(result[x]); // 调用toString()

}

}

}

}

范例1-5:列出指定目录下的所有文件及子目录信息。在每一个目录中有可能还会存在其他子目录,并且还可能有更深层次的子目录,所以为了可以列出所有的内容,应该判断每一个给定的路径是否是目录。如果是目录则应该继续列出,这样的操作最好使用递归的方式完成。

package com.yootk.demo;

import java.io.File;

public class TestDemo {

public static void main(String[] args) throws Exception { // 此处直接抛出

File file = new File("c:" + File.separator); // 定义操作路径

print(file); // 列出目录

}

/**

* 列出目录结构,此方法采用递归调用形式

* @param file 要列出目录的路径

*/

public static void print(File file) {

if (file.isDirectory()) { // 路径为目录

File result[] = file.listFiles(); // 列出子目录

if (result != null) { // 目录可以列出

for (int x = 0; x < result.length; x++) {

print(result[x]); // 递归调用

}

}

}

System.out.println(file); // 直接输出完整路径

}

}

1.2  字节流与字符流

范例1-6:自动执行close()操作。

package com.yootk.demo;

class Net implements AutoCloseable {

@Override

public void close() throws Exception {

System.out.println("*** 网络资源自动关闭,释放资源。");

}

public void info() throws Exception { // 假设有异常抛出

System.out.println("*** 欢迎访问:www.yootk.com");

}

}

public class TestDemo {

public static void main(String[] args) {

try (Net n = new Net()){

n.info();

} catch (Exception e) {

e.printStackTrace();

}

}

}

范例1-7:文件内容的输出。

package com.yootk.demo;

import java.io.File;

import java.io.FileOutputStream;

import java.io.OutputStream;

public class TestDemo {

public static void main(String[] args) throws Exception { // 直接抛出

// 1.定义要输出文件的路径

File file = new File("d:" + File.separator + "demo" + File.separator

+ "mldn.txt");

// 此时由于目录不存在,所以文件不能输出,应该首先创建目录

if (!file.getParentFile().exists()) { // 文件目录不存在

file.getParentFile().mkdirs(); // 创建目录

}

// 2.应该使用OutputStream和其子类进行对象的实例化,此时目录存在,文件还不存在

OutputStream output = new FileOutputStream(file);

// 字节输出流需要使用byte类型,需要将String类对象变为字节数组

String str = "更多课程资源请访问:www.yootk.com";

byte data[] = str.getBytes(); // 将字符串变为字节数组

output.write(data); // 3.输出内容

output.close(); // 4.资源操作的最后一定要进行关闭

}

}

范例1-8:文件追加。

// 2.应该使用OutputStream和其子类进行对象的实例化,此时目录存在,文件还不存在

OutputStream output = new FileOutputStream(file,true) ;

范例1-9:采用单个字节的方式输出(此处可以利用循环操作输出全部字节数组中的数据)。

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

output.write(data[x]); // 内容输出

}

范例1-10:输出部分字节数组内容(设置数组的开始索引和长度)。

output.write(data, 6, 6); // 内容输出

范例1-11:数据读取操作。

package com.yootk.demo;

import java.io.File;

import java.io.FileInputStream;

import java.io.InputStream;

public class TestDemo {

public static void main(String[] args) throws Exception { // 直接抛出

File file = new File("d:" + File.separator + "demo" + File.separator

+ "mldn.txt"); // 1.定义要输出文件的路径

if (file.exists()) { // 需要判断文件是否存在后才可以进行读取

// 2.使用InputStream进行读取

InputStream input = new FileInputStream(file) ;

byte data [] = new byte [1024] ; // 准备出一个1024的数组

int len = input.read(data) ; // 3.进行数据读取,将内容保存到字节数组中

input.close(); // 4.关闭输入流

// 将读取出来的字节数组数据变为字符串进行输出

System.out.println("【" + new String(data,0,len) + "】");

}

}

}

范例1-12:采用while循环实现输入流操作。

package com.yootk.demo;

import java.io.File;

import java.io.FileInputStream;

import java.io.InputStream;

public class TestDemo {

public static void main(String[] args) throws Exception { // 直接抛出

File file = new File("d:" + File.separator + "demo" + File.separator

+ "mldn.txt"); // 1.定义要输出文件的路径

if (file.exists()) { // 需要判断文件是否存在后才可以进行读取

// 2.使用InputStream进行读取

InputStream input = new FileInputStream(file) ;

byte data [] = new byte [1024] ; // 准备出一个1024的数组

int foot = 0 ; // 表示字节数组的操作脚标

int temp = 0 ; // 表示接收每次读取的字节数据

// 第一部分:(temp = input.read()),表示将read()方法读取的字节内容给temp变量

// 第二部分:(temp = input.read()) != -1,判断读取的temp内容是否是-1

while((temp = input.read()) != -1) { // 3.读取数据

data[foot ++] = (byte) temp ; // 有内容进行保存

}

input.close(); // 4.关闭输入流

System.out.println("【" + new String(data,0,foot) + "】");

}

}

}

范例1-13:利用dowhile实现数据读取。

byte data [] = new byte [1024] ; // 准备出一个1024的数组

int foot = 0 ; // 表示字节数组的操作脚标

int temp = 0 ; // 表示接收每次读取的字节数据

do {

temp = input.read() ; // 读取一个字节

if (temp != -1) { // 现在是真实的内容

data[foot ++] = (byte) temp ; // 保存读取的字节到数组中

}

} while (temp != -1) ; // 如果现在读取的temp的字节数据不是-1,表示还有内容

范例1-14:使用Writer类实现内容输出

package com.yootk.demo;

import java.io.File;

import java.io.FileWriter;

import java.io.Writer;

public class TestDemo {

public static void main(String[] args) throws Exception { // 此处直接抛出

File file = new File("d:" + File.separator + "demo" + File.separator

+ "mldn.txt"); // 1.定义要输出文件的路径

if (!file.getParentFile().exists()) { // 判断目录是否存在

file.getParentFile().mkdirs(); // 创建文件目录

}

Writer out = new FileWriter(file); // 2.实例化了Writer类的对象

String str = "更多课程请访问:www.yootk.com"; // 定义输出内容

out.write(str); // 3.输出字符串数据

out.close(); // 4.关闭输出流

}

}

范例1-15:使用Reader读取数据。

package com.yootk.demo;

import java.io.File;

import java.io.FileReader;

import java.io.Reader;

public class TestDemo {

public static void main(String[] args) throws Exception { // 此处直接抛出

File file = new File("d:" + File.separator + "demo" + File.separator

+ "mldn.txt"); // 1.定义要输出文件的路径

if (file.exists()) {

Reader in = new FileReader(file) ; // 2.为Reader类对象实例化

char data [] = new char [1024] ; // 开辟字符数组,接收读取数据

int len = in.read(data) ; // 3.进行数据读取

in.close(); // 4.关闭输入流

System.out.println(new String(data, 0, len));

}

}

}

范例1-16:强制清空字符流缓冲区。

package com.yootk.demo;

import java.io.File;

import java.io.FileWriter;

import java.io.Writer;

public class TestDemo {

public static void main(String[] args) throws Exception { // 此处直接抛出

File file = new File("d:" + File.separator + "demo" + File.separator

+ "mldn.txt"); // 1.定义要输出文件的路径

if (!file.getParentFile().exists()) { // 判断目录是否存在

file.getParentFile().mkdirs(); // 创建文件目录

}

Writer out = new FileWriter(file); // 2.实例化了Writer类的对象

String str = "更多课程请访问:www.yootk.com"; // 定义输出内容

out.write(str); // 3.输出字符串数据

out.flush(); // 强制刷新缓冲区

}

}

1.3  转换流

范例1-17:实现输出流转换。

package com.yootk.demo;

import java.io.File;

import java.io.FileOutputStream;

import java.io.OutputStream;

import java.io.OutputStreamWriter;

import java.io.Writer;

public class TestDemo {

public static void main(String[] args) throws Exception { // 此处直接抛出

File file = new File("d:" + File.separator + "demo" + File.separator

+ "mldn.txt"); // 1.定义要输出文件的路径

if (!file.getParentFile().exists()) { // 判断父路径是否存在

file.getParentFile().mkdirs() ; // 创建父路径

}

OutputStream output = new FileOutputStream(file) ;// 字节流

// 将OutputStream类对象传递给OutputStreamWriter类的构造方法,而后向上转型为Writer

Writer out = new OutputStreamWriter(output) ;

out.write("更多课程请访问:www.yootk.com"); // Writer类的方法

out.flush();

out.close();

}

}

1.4  案例:文件复制

范例1-18:实现文件复制操作。

package com.yootk.demo;

import java.io.File;

import java.io.FileInputStream;

import java.io.FileOutputStream;

import java.io.InputStream;

import java.io.OutputStream;

public class CopyDemo {

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

long start = System.currentTimeMillis() ; // 取得复制开始的时间

if (args.length != 2) { // 初始化参数不足2位

System.out.println("命令执行错误!");

System.exit(1); // 程序退出执行

}

// 如果输入参数正确,应该进行源文件有效性的验证

File inFile = new File(args[0]) ; // 第一个为源文件路径

if (!inFile.exists()) { // 源文件不存在

System.out.println("源文件不存在,请确认执行路径。");

System.exit(1); // 程序退出

}

// 如果此时源文件正确,就需要定义输出文件,同时要考虑到输出文件有目录

File outFile = new File(args[1]) ;

if (!outFile.getParentFile().exists()) { // 输出文件路径不存在

outFile.getParentFile().mkdirs() ; // 创建目录

}

// 实现文件内容的复制,分别定义输出流与输入流对象

InputStream input = new FileInputStream(inFile) ;

OutputStream output = new FileOutputStream(outFile) ;

int temp = 0 ; // 保存每次读取的数据长度

byte data [] = new byte [1024] ; // 每次读取1024个字节

// 将每次读取进来的数据保存在字节数组里面,并且返回读取的个数

while((temp = input.read(data)) != -1) { // 循环读取数据

output.write(data, 0, temp); // 输出数组

}

input.close(); // 关闭输入流

output.close(); // 关闭输出流

long end = System.currentTimeMillis() ; // 取得操作结束时间

System.out.println("复制所花费的时间:" + (end - start));

}

}

1.5  字符编码

范例1-19:取得当前系统中的环境属性中的文件编码。

package com.yootk.demo;

public class TestDemo {

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

System.getProperties().list(System.out); // 列出全部系统属性

}

}

范例1-20:程序出现乱码。

package com.yootk.demo;

import java.io.File;

import java.io.FileOutputStream;

import java.io.OutputStream;

public class TestDemo {

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

File file = new File("D:" + File.separator + "mldn.txt");

OutputStream output = new FileOutputStream(file);

// 强制改变文字的编码,此操作可以通过String类的getBytes()方法实现

output.write("更多课程请访问:www.yootk.com".getBytes("ISO8859-1"));

output.close();

}

}

1.6  内存流

范例1-21:实现一个小写字母转大写字母的操作。

·  本程序不使用String类中提供的toUpperCase()方法,而是利用IO操作,将每一个字节进行大写字母转换;

·  为了方便地实现字母的转大写操作(避免不必要的字符也被转换)可以借助Character包装类的方法。

|- 转小写字母:public static char toLowerCase(char ch);

|- 转小写字母(利用字母编码转换):public static int toLowerCase(int codePoint);

|- 转大写字母:public static char toUpperCase(char ch);

|- 转大写字母(利用字母编码转换):public static int toUpperCase(int codePoint)。

package com.yootk.demo;

import java.io.ByteArrayInputStream;

import java.io.ByteArrayOutputStream;

import java.io.InputStream;

import java.io.OutputStream;

public class TestDemo {

public static void main(String[] args) throws Exception { // 此处直接抛出

String str = "www.yootk.com & www.MLDN.cn"; // 要求被转换的字符串

// 本次将通过内存操作流实现转换,先将数据保存在内存流里面,再从里面取出每一个数据

// 将所有要读取的数据设置到内存输入流中,本次利用向上转型为InputStream类实例化

InputStream input = new ByteArrayInputStream(str.getBytes());

// 为了能够将所有的内存流数据取出,可以使用ByteArrayOutputStream

OutputStream output = new ByteArrayOutputStream();

int temp = 0; // 读取每一个字节数据

// 经过此次循环后,所有的数据都将保存在内存输出流对象中

while ((temp = input.read()) != -1) { // 每次读取一个数据

// 将读取进来的数据转换为大写字母,利用Character.toUpperCase()可以保证只转换字母

output.write(Character.toUpperCase(temp)); // 字节输出流

}

System.out.println(output); // 调用toString()方法

input.close(); // 关闭输入流

output.close(); // 关闭输出流

}

}

范例1-22:实现文件的合并读取。

package com.yootk.demo;

import java.io.ByteArrayOutputStream;

import java.io.File;

import java.io.FileInputStream;

import java.io.InputStream;

public class TestDemo {

public static void main(String[] args) throws Exception { // 异常简化处理

File fileA = new File("D:" + File.separator + "infoa.txt"); // 文件路径

File fileB = new File("D:" + File.separator + "infob.txt"); // 文件路径

InputStream inputA = new FileInputStream(fileA); // 字节输入流

InputStream inputB = new FileInputStream(fileB); // 字节输入流

ByteArrayOutputStream output = new ByteArrayOutputStream(); // 内存输出流

int temp = 0; // 每次读取一个字节

while ((temp = inputA.read()) != -1) { // 循环读取数据

output.write(temp); // 将数据保存到输出流

}

while ((temp = inputB.read()) != -1) { // 循环读取数据

output.write(temp); // 将数据保存到输出流

}

// 现在所有的内容都保存在了内存输出流里面,所有的内容变为字节数组取出

byte data[] = output.toByteArray(); // 取出全部数据

output.close(); // 关闭输出流

inputA.close(); // 关闭输入流

inputB.close(); // 关闭输入流

System.out.println(new String(data)); // 字节转换为字符串输出

}

}

1.7  打印流

范例1-23:定义打印流工具类

package com.yootk.demo;

import java.io.File;

import java.io.FileOutputStream;

import java.io.IOException;

import java.io.OutputStream;

class PrintUtil { // 实现专门的输出操作功能

private OutputStream output ; // 输出只能依靠OutputStream

/**

* 输出流的输出目标要通过构造方法传递

* @param output

*/

public PrintUtil(OutputStream output) {

this.output = output ;

}

public void print(int x) { // 输出int型数据

this.print(String.valueOf(x)); // 调用本类字符串的输出方法

}

public void print(String x) {

try { // 采用OutputStream类中定义的方法,将字符串转变为字节数组后输出

this.output.write(x.getBytes());

} catch (IOException e) {

e.printStackTrace();

}

}

public void print(double x) { // 输出double型数据

this.print(String.valueOf(x));

}

public void println(int x) { // 输出数据后换行

this.println(String.valueOf(x));

}

public void println(String x) { // 输出数据后换行

this.print(x.concat("\n"));

}

public void println(double x) {

this.println(String.valueOf(x));

}

public void close() { // 输出流关闭

try {

this.output.close();

} catch (IOException e) {

e.printStackTrace();

}

}

}

public class TestDemo {

public static void main(String[] args) throws Exception { // 此处直接抛出

PrintUtil pu = new PrintUtil(new FileOutputStream(new File("d:"

+ File.separator + "yootk.txt")));

pu.print("优拓教育:");

pu.println("www.yootk.com");

pu.println(1 + 1);

pu.println(1.1 + 1.1);

pu.close();

}

}

范例1-24:使用PrintStream类实现输出。

package com.yootk.demo;

import java.io.File;

import java.io.FileOutputStream;

import java.io.PrintStream;

public class TestDemo {

public static void main(String[] args) throws Exception { // 此处直接抛出

// 实例化PrintStream类对象,本次利用FileOutputStream类实例化PrintStream类对象

PrintStream pu = new PrintStream(new FileOutputStream(new File("d:"

+ File.separator + "yootk.txt")));

pu.print("优拓教育:");

pu.println("www.yootk.com");

pu.println(1 + 1);

pu.println(1.1 + 1.1);

pu.close();

}

}

范例1-25:格式化输出。

package com.yootk.demo;

import java.io.File;

import java.io.FileOutputStream;

import java.io.PrintStream;

public class TestDemo {

public static void main(String[] args) throws Exception { // 此处直接抛出

String name = "李兴华";

int age = 19;

double score = 59.95891023456;

PrintStream pu = new PrintStream(new FileOutputStream(new File("d:"

+ File.separator + "yootk.txt")));

pu.printf("姓名:%s,年龄:%d,成绩:%5.2f", name, age, score);

pu.close();

}

}

范例1-26:格式化字符串。

package com.yootk.demo;

public class TestDemo {

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

String name = "李兴华";

int age = 19;

double score = 59.95891023456;

String str = String.format("姓名:%s,年龄:%d,成绩:%5.2f", name, age, score);

System.out.println(str);

}

}

1.8  System类对IO的支持

范例1-27:错误输出。

package com.yootk.demo;

public class TestDemo {

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

try {

Integer.parseInt("abc"); // 此处一定会发生异常

} catch (Exception e) {

System.err.println(e); // 错误输出

}

}

}

范例1-28:利用OutputStream实现屏幕输出。

package com.yootk.demo;

import java.io.OutputStream;

public class TestDemo {

public static void main(String[] args) throws Exception { // 此处直接抛出异常

OutputStream out = System.out; // OutputStream就为屏幕输出

out.write("www.yootk.com".getBytes()); // 屏幕输出

}

}

范例1-29:消费型函数式接口与方法引用。

package com.yootk.demo;

import java.util.function.Consumer;

public class TestDemo {

public static void main(String[] args) throws Exception { // 此处直接抛出

Consumer<String> con = System.out::println; // 方法引用

con.accept("更多课程请访问:www.yootk.com"); // 输出

}

}

范例1-30:实现键盘的数据输入。

package com.yootk.demo;

import java.io.InputStream;

public class TestDemo {

public static void main(String[] args) throws Exception { // 此处直接抛出

// 为了方便读者理解,本处将System.in使用InputStream接收,但实际上不需要此操作

InputStream input = System.in; // System.in为InputStream类实例

byte data[] = new byte[1024]; // 开辟空间接收数据

System.out.print("请输入数据:"); // 信息提示,此处没有换行

int len = input.read(data); // 读取数据并返回长度

System.out.println("输入数据为:" + new String(data, 0, len));

}

}

范例1-31:改进输入操作设计。

package com.yootk.demo;

import java.io.InputStream;

public class TestDemo {

public static void main(String[] args) throws Exception { // 此处直接抛出异常

InputStream input = System.in ;

StringBuffer buf = new StringBuffer(); // 接收输入数据

System.out.print("请输入数据:"); // 提示信息

int temp = 0; // 接收每次读取数据长度

while ((temp = input.read()) != -1) { // 判断是否有输入数据

if (temp == '\n') { // 判断是否为回车符

break; // 停止接收

}

buf.append((char) temp); // 保存读取数据

}

System.out.println("输入数据为:" + buf); // 输出内容

}

}

1.9  字符缓冲流:BufferedReader

范例1-32:键盘数据输入的标准格式。

package com.yootk.demo;

import java.io.BufferedReader;

import java.io.InputStreamReader;

public class TestDemo {

public static void main(String[] args) throws Exception { // 此处直接抛出

// System.in是InputStream类对象,BufferedReader的构造方法里面需要接收Reader类对象

// 利用InputStreamReader将字节流对象变为字符流对象

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

System.out.print("请输入数据:");

String str = buf.readLine(); // 以回车作为换行

System.out.println("输入的内容:" + str);

}

}

范例1-33:判断输入内容。

package com.yootk.demo;

import java.io.BufferedReader;

import java.io.InputStreamReader;

public class TestDemo {

public static void main(String[] args) throws Exception { // 此处直接抛出

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

boolean flag = true; // 编写一个循环的逻辑

while (flag) { // 判断标志位

System.out.print("请输入年龄:"); // 提示信息

String str = buf.readLine(); // 以回车作为换行

if (str.matches("\\d{1,3}")) { // 输入数据由数字组成

System.out.println("年龄是:" + Integer.parseInt(str));

flag = false ; // 退出循环

} else {

System.out.println("年龄输入错误,应该由数字所组成。");

}

}

}

}

范例1-34:读取文件。

package com.yootk.demo;

import java.io.BufferedReader;

import java.io.File;

import java.io.FileReader;

public class TestDemo {

public static void main(String[] args) throws Exception { // 此处直接抛出

File file = new File("D:" + File.separator + "yootk.txt");

// 使用文件输入流实例化BufferedReader类对象

BufferedReader buf = new BufferedReader(new FileReader(file));

String str = null; // 接收输入数据

while ((str = buf.readLine()) != null) { // 读取数据并判断是否存在

System.out.println(str); // 输出读取内容

}

buf.close();

}

}

1.10  扫描流:Scanner

范例1-35:利用Scanner实现键盘数据输入。

package com.yootk.demo;

import java.util.Scanner;

public class TestDemo {

public static void main(String[] args) throws Exception { // 此处直接抛出

Scanner scan = new Scanner(System.in); // 准备接收键盘输入数据

System.out.print("请输入内容:"); // 提示信息

if (scan.hasNext()) { // 是否有输入数据

System.out.println("输入内容:" + scan.next()); // 存在内容则输出

}

scan.close();

}

}

范例1-36:输入一个数字double。

package com.yootk.demo;

import java.util.Scanner;

public class TestDemo {

public static void main(String[] args) throws Exception { // 此处直接抛出

Scanner scan = new Scanner(System.in); // 准备接收键盘输入数据

System.out.print("请输入成绩:");

if (scan.hasNextDouble()) { // 表示输入的是一个小数

double score = scan.nextDouble(); // 省略了转型

System.out.println("输入内容:" + score);

} else { // 表示输入的不是一个小数

System.out.println("输入的不是数字,错误!");

}

scan.close();

}

}

范例1-37:正则验证。

package com.yootk.demo;

import java.util.Scanner;

public class TestDemo {

public static void main(String[] args) throws Exception { // 此处直接抛出

Scanner scan = new Scanner(System.in) ; // 准备接收键盘输入数据

System.out.print("请输入生日:"); // 提示文字

if (scan.hasNext("\\d{4}-\\d{2}-\\d{2}")) { // 正则验证

String bir = scan.next("\\d{4}-\\d{2}-\\d{2}") ; // 接收数据

System.out.println("输入内容:" + bir);

} else { // 数据格式错误

System.out.println("输入的生日格式错误!");

}

scan.close();

}

}

范例1-38:读取文件。

package com.yootk.demo;

import java.io.File;

import java.io.FileInputStream;

import java.util.Scanner;

public class TestDemo {

public static void main(String[] args) throws Exception { // 此处直接抛出

Scanner scan = new Scanner(new FileInputStream(new File("D:"

+ File.separator + "yootk.txt"))); // 设置读取的文件输入流

scan.useDelimiter("\n"); // 设置读取的分隔符

while (scan.hasNext()) { // 循环读取

System.out.println(scan.next()); // 直接输出读取数据

}

scan.close();

}

}

1.11  对象序列化

范例1-39:定义一个可以被序列化对象的类。

package com.yootk.demo;

import java.io.Serializable;

@SuppressWarnings("serial") // 压制序列化版本号警告信息

class Book implements Serializable { // 此类对象可以被序列化

private String title;

private double price;

public Book(String title, double price) {

this.title = title;

this.price = price;

}

@Override

public String toString() {

return "书名:" + this.title + ",价格:" + this.price;

}

}

范例1-40:实现序列化对象操作ObjectOutputStream。

package com.yootk.demo;

import java.io.File;

import java.io.FileOutputStream;

import java.io.ObjectOutputStream;

public class TestDemo {

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

ser();

}

public static void ser() throws Exception {

ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(

new File("D:" + File.separator + "book.ser")));

oos.writeObject(new Book("Java开发实战经典", 79.8)); // 序列化对象

oos.close();

}

}

范例1-41:实现反序列化操作ObjectInputStream。

package com.yootk.demo;

import java.io.File;

import java.io.FileInputStream;

import java.io.ObjectInputStream;

public class TestDemo {

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

dser();

}

public static void dser() throws Exception {

ObjectInputStream ois = new ObjectInputStream(

new FileInputStream(new File("D:" + File.separator + "book.ser")));

Object obj = ois.readObject() ; // 反序列化对象

Book book = (Book) obj ; // 转型

System.out.println(book);

ois.close();

}

}

范例1-42:定义不需要序列化的属性。

package com.yootk.demo;

import java.io.Serializable;

@SuppressWarnings("serial")

class Book implements Serializable { // 此类对象可以被序列化

private transient String title; // 此属性无法被序列化

private double price;

public Book(String title, double price) {

this.title = title;

this.price = price;

}

@Override

public String toString() {

return "书名:" + this.title + ",价格:" + this.price;

}

}

Java_09 快速入门 Java IO编程相关推荐

  1. java学习_Java编程学习难不难 怎样才能快速入门Java

    Java编程学习难不难?怎样才能快速入门Java?对于想要加入IT行业的人来说,Java是一个不错的选择,不仅人才需求大,就业薪资也非常不错.许多人都非常看好Java发展前景,接下来千锋小编就给大家介 ...

  2. 好程序员Java培训分享如何快速入门Java编程

    好程序员Java培训分享如何快速入门Java编程,作为老牌编程语言,Java拥有广阔的市场应用,企业对Java人才的需求一直居高不下.有很多非专业.零基础的人想要学习Java却不知道怎么快速入门,接下 ...

  3. Java IO编程全解(五)——AIO编程

    转载请注明出处:http://www.cnblogs.com/Joanna-Yan/p/7794151.html 前面讲到:Java IO编程全解(四)--NIO编程 NIO2.0引入了新的异步通道的 ...

  4. Java IO编程全解(六)——4种I/O的对比与选型

    转载请注明出处:http://www.cnblogs.com/Joanna-Yan/p/7804185.html 前面讲到:Java IO编程全解(五)--AIO编程 为了防止由于对一些技术概念和术语 ...

  5. Java好学吗?Java能做什么?如何快速入门Java?

    Java是一门面向对象编程语言,不仅吸收了C++语言的各种优点,还摒弃了C++里难以理解的多继承.指针等概念,Java具有简单性.面向对象.分布式.健壮性.安全性.平台独立与可移植性.多线程.动态性等 ...

  6. 视频教程-Spring boot快速入门-Java

    Spring boot快速入门 十年项目开发经验,主要从事java相关的开发,熟悉各种mvc开发框架. 王振伟 ¥12.00 立即订阅 扫码下载「CSDN程序员学院APP」,1000+技术好课免费看 ...

  7. Java IO 编程

    Java IO 编程 提供了大量的Input和output 方法. 一个类File 和五个接口四个抽象类 File 类 唯一一个与文件本身操作的类,这个类可以进行操作文件路径的指派,可以创建或者删除文 ...

  8. java IO编程详解

    java IO编程详解 一.Socket 1. Sock概述 Socket,套接字就是两台主机之间逻辑连接的端点.TCP/IP协议是传输层协议,主要解决数据如何在网络中传输,而HTTP协议是应用层协议 ...

  9. 【Java基础】Java IO编程:输入输出流、内存流、打印流、缓冲流BufferedReader、扫描流Scanner、序列化与反序列化

    文章目录 第11章.Java IO编程 11.1 文件操作类:File 11.2 字节流与字符流 字节输出流:OutputStream OutputStream类 FileOutputStream类 ...

最新文章

  1. Adobe flash cs5 的Java运行时环境初始化错误 完美解决方法
  2. Objective-C中的Category
  3. Linux Shell编程入门(zz)
  4. SpringBoot运行时提示:Error starting ApplicationContexxt,To display the uto-configration report re-run you
  5. 我让代码生了个孩子继承了他爸爸谁知他爸爸继承了他爷爷(16)
  6. azure云数据库_如何将MySQL表迁移到Microsoft Azure SQL数据库
  7. bzoj2843极地旅行社题解
  8. 《深入浅出struts》读书笔记(3)
  9. 最新python腾讯文档界面自动打卡
  10. 已解决:录屏软件录不了全屏的问题
  11. html右下角的广告特效,用jQuery实现网页右下角弹出广告效果
  12. Calendar 设置周一为每周第一天
  13. TOP3款最好用的 Bootstrap 可视化开发工具,我想要的BT知识点都整理好了
  14. THULAC 词性表
  15. mysql error 1114_ERROR 1114 (HY000): The table is full
  16. 获取上传文件的后缀,.jpg,.png,.word,.xsl...使用方法split,lastindexOf,subtr
  17. MATLAB 过时了吗?
  18. 绿联硬盘盒linux驱动,绿联 USB3.0 SATA 接口通用移动硬盘盒子体验与选购技巧
  19. Cadence Virtuoso 原理图仿真报错问题解决
  20. msm8953 LK通过cmdline向Kernel传递LCD参数过程分析

热门文章

  1. 一些提取api key的正则表达式
  2. windows10在BIOS中改AHCI时开机蓝屏解决方案
  3. Problem D: 四阶多项式
  4. librosa.load报错。audioread.NoBackendError
  5. python怎样使用各个日期赤纬_Python常用的日期时间处理方法示例
  6. uboot 或者 linux 下限制 sata speed
  7. 如何制定学习计划 - 褪墨
  8. ZigBee的发展也有“碎片化”zigbee模块
  9. 通过一个命令返回上级多层目录的方法
  10. 微信小程序抓包https抓包的血泪史