示例代码是:-
import java.io.*;
import java.util.List;
import java.util.ArrayList;
public class ListOfNumbers{
private static int Size=10; // this is a class variable- as there should be only 1 instance of the class.
private List<Integer> list;
public ListOfNumbers(){
list = new ArrayList<Integer>(Size); // an arraylist of size-10.
System.out.println("Populating the list");
for(int i =0; i<Size; i++)
{
list.add(new Integer(i)); // is similar to using list.add(i); /* this involves auto-boxing*/
}
System.out.println("List populated");
}
public void writeList(File file){
FileWriter out = null;
try{
out = new FileWriter(file);
System.out.println("Start Writing to the File" + " " +file);
for(int i =0; i < Size; i++)
{
out.write("Value at" + i + "is:" +" " + (list.get(i)).intValue()); //is similar to writing list.get(i) /*this will return Integer, because of AB it will treated int*/
out.write("\n");
}
System.out.println("Contents written to the file");
}
catch(FileNotFoundException fnfex){
fnfex.printStackTrace();
}
catch(IOException ioex){
ioex.printStackTrace();
}
finally{
if(out != null)
{
try{
out.close();
}
catch(IOException ioex)
{
ioex.printStackTrace();
}
}
else
System.out.println("Stream not open");
}
}
public void readList(File file)
{
String pointer = null;
String [] value = null;
RandomAccessFile input = null;
System.out.println("Trying to read from file:" + " " + file);
try{
System.out.println("In the try block");
input= new RandomAccessFile(file,"r"); //should throw exception
System.out.println("Created a reference to the file"+ file);
while((pointer = input.readLine()) !=null) //should throw exception
{
System.out.println("In the while block");
System.out.println(pointer);
value = pointer.split(": ");
list.add(Integer.parseInt(value[1]));
}
}
catch(FileNotFoundException fnfex)
{
fnfex.printStackTrace();
}
catch(IOException ioex)
{
ioex.getMessage();
}
}
public void displayList(){
System.out.println("Displaying List elements");
// list.size();
for(int i=0; i < list.size(); i++){
System.out.println(list.get(i));
}
}
public static void main(String [] par)
{
ListOfNumbers obj = new ListOfNumbers();
File file = new File("Output.txt");
obj.writeList(file);
obj.readList(file);
obj.displayList();
}
}
结果:-
Populating the list
List populated
java.io.FileNotFoundException: Output.txt (Permission denied)
at java.io.FileOutputStream.open(Native Method)
at java.io.FileOutputStream.<init>(FileOutputStream.java:209)
at java.io.FileOutputStream.<init>(FileOutputStream.java:160)
at java.io.FileWriter.<init>(FileWriter.java:90)
at ListOfNumbers.writeList(ListOfNumbers.java:22)
at ListOfNumbers.main(ListOfNumbers.java:97)
Stream not open
Trying to read from file: Output.txt
In the try block
Created a reference to the fileOutput.txt
Displaying List elements
0
1
2
3
4
5
6
7
8
9
我已经更改了权限,Output.txt
以便获得异常。我的问题是为什么当我们尝试访问文件时 readList () 方法不抛出异常,即分配对输入的引用以及尝试在 while 循环中使用它时。