1.题目
// 使用文件字节输出流写文件a.txt
import java.io.*;
public class Example10_5 {
public static void main(String args[]) {
byte [] a = "新年快乐".getBytes();
byte [] b = "Happy New Year".getBytes();
/*************************************************/
File file = new File();
try{
/****************************************************/
OutputStream out=new FileOutputStream();
System.out.println(file.getName()+"的大小:"+file.length()+"字节");
out.write(a);
out.close();
out=new FileOutputStream(file,true);
System.out.println(file.getName()+"的大小:"+file.length()+"字节");
System.out.println(file.getName()+"的大小:"+file.length()+"字节");
out.close();
}
catch(IOException e) {
System.out.println("Error "+e);
}
}
}
1.答案
File file = new File(); 改成 File file = new File(“a.txt”);
OutputStream out=new FileOutputStream(); 改成 OutputStream out=new FileOutputStream(file);
2.题目
public class E_23
{
public static void main(String args[])
{ try
{
int [] a=new int[5];
a[5]=6;
}
/*********************************************/
catch(Exception e)
{System.out.println("该程序发生异常");}
/************************************************/
catch(ArrayIndexOutOfBoundsException e)
{System.out.println("该程序发生数组下标越界异常");}
}
}
2.答案
catch(Exception e) 改成 catch(ArrayIndexOutOfBoundsException e)
catch(ArrayIndexOutOfBoundsException e) 改成 catch(Exception e)
3.题目
//使用文件字节流读文件的内容
import java.io.*;
public class E_24 {
public static void main(String args[]) {
int n=-1;
byte [] a=new byte[100];
try{ File f=new File("E_24.java");
/*************************************************/
InputStream in = new InputStream(f);
/**********************************************/
while((n=in(a,0,100))!=-1) {
String s=new String (a,0,n);
System.out.print(s);
}
in.close();
}
catch(IOException e) {
System.out.println("File read Error"+e);
}
}
}
3.答案
InputStream in = new InputStream(f); 改成 InputStream in = new FileInputStream(f);
//这里的问题在于 InputStream 是一个抽象类,不能直接实例化。我们需要使用 InputStream 的一个具体实现,比如 FileInputStream,来创建一个可以读取文件的输入流。
while((n=in(a,0,100))!=-1) 改成 in.read(a,0,100)
//这里的问题在于 in 是一个 InputStream 类型的对象,而 InputStream 类没有定义 in 方法。正确的做法是调用 InputStream 类的 read 方法来读取数据。
4.题目
public class E_25
{
public static void main(String args[])
{
try
{
int[ ] a=new int[5];
a[0]=6;
}
/********************************************/
finally(ArrayIndexOutOfBoundsException e)
{System.out.println("该程序发生数组下标越界异常");}
catch(Exception ee)
{System.out.println("该程序发生异常");}
/**************************************************/
catch
{System.out.println("该语句是肯定执行的");}
}
}
4.答案
finally(ArrayIndexOutOfBoundsException e) 改成 catch(ArrayIndexOutOfBoundsException e)
catch
{System.out.println(“该语句是肯定执行的”);}
}
改成
finally
{System.out.println(“该语句是肯定执行的”);}
}