输入输出
Java中有以下三种标准输入输出流:
- 标准输入 System.in
- 标准输出 System.out
- 标准错误输出 System.err
import java.io.*;
public class Echo {
public static void main(String [] args)
throws IOException{
BufferedReader in =
new BufferedReader(new InputStreamReader(System.in));
String s;
while ((s=in.readLine()).length()!=0){
System.out.println(s);
}
}
}
这里使用的System.in是在程序启动时由java系统自动创建的流对象,由于它是原始的字节流,因而不能直接从中读取字符,需要对其做进一步的处理。
本例中以System.in作为参数,进一步创建了一个InputStreamReader流对象,InputStreamReader相当于字节流和字符流之间的一座桥梁,它读取字节将其转换为字符。BufferedReader用于对InputStreamReader处理后的信息进行缓冲,以提高效率。
异常处理
异常又称为例外,是特殊的运行错误对象。Java通过面向对象的方法来处理程序错误,为可能发生非致命性错误设计错误处理模块,将错误作为预定义好的“异常”捕获,然后传递给专门的错误处理模块进行处理。
运行时系统在方法的调用栈中查找,从生成异常的方法开始进行回溯,直到找到包含相应异常处理的方法为止,这一过程称为捕获(catch)一个异常。
捕获异常:try、catch 和 finally语句
使用try语句括住可能抛出异常的代码段,用catch语句指明要捕获的异常及相应的处理代码。
try与catch语句的语法格式如下:
try{
//此处为抛出具体异常的代码
}catch(ExceptionType1 e){
//抛出ExceptionType1异常时要执行的代码
}catch(ExceptionType2 e){
//抛出ExceptionType2异常时要执行的代码
...
}catch(ExceptionTypek e){
//抛出ExceptionTypek异常时要执行的代码
}finally{
//必须执行的代码
}
其中,ExceptionType1、ExceptionType2 … ExceptionTypek是产生的异常类型。在运行时,根据发生异常所属的类,找到对应的catch语句,然后执行其后的语句序列,Finally块的作用通常用于释放资源,Finally不是必须必需的部分,如果有finally部分,不论是否捕获到异常,总要执行finlly后面的语句。
import java.io.*;
public class Keyboard {
static BufferedReader inputStream=new BufferedReader(new InputStreamReader(System.in));
public static int getInteger(){
try {
return (Integer.valueOf(inputStream.readLine().trim()).intValue());
}catch (Exception e){
e.printStackTrace();
return 0;
}
}
public static String getString(){
try{
return (inputStream.readLine());
}catch (IOException e){
return "0";
}
}
}
import java.io.*;
public class ExceptionTester {
public static void main(String args[]){
int result;
int num[]=new int[2];
boolean valid;
for (int i=0;i<2;i++){
valid=false;
while (!valid){
try{
System.out.println("Enter number "+(i+1));
num[i]=Integer.valueOf(Keyboard.getString()).intValue();
valid=true;
}catch (NumberFormatException e){
System.out.println("Invalid interger enter.Please try again.");
}
}
}
try {
result=num[0]/num[1];
System.out.println(num[0]+"/"+num[1]+"="+result);
}catch (ArithmeticException e){
System.out.println("Second num is 0,cannot do division.");
}
}
}
输出结果:
Enter number 1
a
Invalid interger enter.Please try again.
Enter number 1
123
Enter number 2
f
Invalid interger enter.Please try again.
Enter number 2
0
Second num is 0,cannot do division.
Java中异常真是多种多样,这些异常之间彼此有关联。
throws & throw
如果程序员不想在当前方法内处理异常,可以使用throws子句声明将异常抛出到调用方法中。
public class className {
public void deposit(double amount) throws RemoteException {
// Method implementation
throw new RemoteException();
}
//Remainder of class definition
}
throws关键字要写在会出现异常的方法后面,并定义好会出现的异常类型,如有多个异常,则用逗号隔开。这样我们就可以将处理异常这种麻烦事交给上层处理啦。
如果我们要创建一个自定义的异常,我们可以使用throw关键字来扔出一个异常:
public class ThrowTest {
public static void main(String args[]){
try{
throw new ArithmeticException();
}catch (ArithmeticException ae){
System.out.println(ae);
}
try{
throw new ArrayIndexOutOfBoundsException();
}catch (ArrayIndexOutOfBoundsException ai){
System.out.println(ai);
}
}
}
输出结果:
java.lang.ArithmeticException
java.lang.ArrayIndexOutOfBoundsException
文件读写File类
File类是IO包中唯一表示磁盘文件信息的对象,它定义了一些与平台无关的方法来操纵文件。通过调用File类提供的各种方法,能够创建、删除文件、重命名文件、判断文件的读写权限及是否存在,设置和查询文件的最近的修改时间等。
创建/删除文件
实例,在电脑桌面上创建文件hello.txt,如果存在则删除旧文件,不存在直接创建新的。
import java.io.*;
public class FileTester {
public static void main(String [] args){
File f=new File("/Users/abel/Desktop"+File.separator+"hello.txt");
if(f.exists()){
f.delete();
System.out.println("File exists,delete it.");
}else{
System.out.println("File not exists,try to create it.");
try{
f.createNewFile();
}catch (Exception e){
System.out.println(e.getMessage());
}
}
}
}
写文本文件
为了在磁盘上写入字符数据,需要用到FileWrite类。
import java.io.*;
public class FileWriterTester {
public static void main(String [] args) throws IOException{
//main方法中声明抛出I/O异常
String fileName="hello.txt";
FileWriter writer=new FileWriter(fileName);//创建一个给定文件名的输出流对象
writer.write("hello!\n");
writer.write("java.\n");
writer.write("你好,世界!\n");
writer.close();//关闭流
}
}
import java.io.*;
public class FileWriterTester {
public static void main(String [] args){
//main方法中声明抛出I/O异常
String fileName="hello.txt";
try{
FileWriter writer=new FileWriter(fileName);//创建一个给定文件名的输出流对象
writer.write("hello!\n");
writer.write("java.\n");
writer.write("你好,世界!\n");
writer.close();//关闭流
}catch (IOException iox){//如果文件操作出现错误,则屏幕显示提示信息
System.out.println("problem writing"+fileName);
}
}
}
读文本文件
从文本文件中读取字符需要使用FileReader类,它继承自Reader抽象类的子类InputStreamReader。对应于写文本文件的缓冲器,读文本文件也有缓冲器类Buffered Reader,具有readLine()函数,可以对换行符进行鉴别,一行一行地读取输入流中的内容。
import java.io.*;
public class BufferedReaderTester {
public static void main(String [] args){
String fileName="hello.txt";
String line;
try{ //创建文件输入流并放入缓冲流当中
BufferedReader in=new BufferedReader(new FileReader(fileName));
line=in.readLine(); //读取一行内容
while (line!=null){ //控制循环条件直到文件终点
System.out.println(line);
line=in.readLine();
}
in.close();
}catch(IOException iox){
System.out.println("problem reading "+fileName);
}
}
}