java输入输出.pptx
文本预览下载声明
第9章 输入/输出;一、基础知识;二、字节流;字节流输入
字节流输入的方法由 InputStream 定义:
;import java.io.*;
public class Example {
public static void main(String[] args) {
try {
byte data[] = new byte[10];
System.out.print(请输入字节串:); int num = System.in.read(data);
for (int i = 0; i num; i++)
System.out.print((char) data[i]);
System.out.println();
} catch (IOException ex) {
System.err.println(异常!);
}
}
};字节流输出
字节流输出的方法由 OutputStream 定义:
;public class Example {
public static void main(String[] args) {
byte data[] = new byte[4];
data[0] = a;
data[1] = b;
data[2] = 90;
data[3] = 100;
for (int i = 0; i 4; i++)
System.out.write((char) data[i]);
System.out.println();
}
};三、字节流文件I/O;import java.io.*;
public class Example {
public static void main(String[] args) {
FileInputStream fin = null; int b = -1;
try {
fin = new FileInputStream(d:\\a.txt);
do {
b = fin.read();
if (b != -1) System.out.print((char) b);
} while (b != -1);
} catch (FileNotFoundException ex) {
ex.printStackTrace();
} catch (IOException ep) {
ep.printStackTrace();
} finally {
try { if (fin != null) fin.close(); }
catch (IOException e) { e.printStackTrace(); }
}
}
};写入文件
创建 FileOutputStream 对象
FileOutputStream 对象 = new FileOutputStream(文件名[, 追加]);
如果追加参数值为 true,则从文件末尾继续写入,否则覆盖。
文件不存在且创建文件失败则抛出 FileNotFoundException 异常。
使用 write 方法写入文件
对象.write(字节内容);
错误抛出 IOException 异常。
关闭文件
对象.close();
错误则抛出 IOException 异常。;import java.io.*;
public class Example {
public static void main(String[] args) {
FileOutputStream fout = null;
try {
fout = new FileOutputStream(d:\\a.txt, false);
} catch (FileNotFoundException ex) {
ex.printStackTrace();
}
try {
fout.write(120);
} catch (IOException ex) {
ex.printStackTrace();
} finally {
try { fout.close(); } catch (IOException e) {
e.printStackTrace();
}
}
}
};自动关闭文件
使用 try-with-resource 语句,可以自动关闭打开的文件,从而省略 close 方法。
try (文件对象声明和初始化语句) {
使用文件对象;
} catch (异常) {
… …
} fin
显示全部