问题描述
我已经在这个程序上工作了很长一段时间,我的大脑被炸了.我可以向正在查看的人寻求帮助.
I have been working on this program for quite sometime and my brain is fried. I could use some help from someone looking in.
我正在尝试制作一个逐行读取文本文件的程序,并且每一行都被制成一个 ArrayList
以便我可以访问每个令牌.我究竟做错了什么?
I'm trying to make a program that reads a text file line by line and each line is made into an ArrayList
so I can access each token. What am I doing wrong?
import java.util.*;
import java.util.ArrayList;
import java.io.*;
import java.rmi.server.UID;
import java.util.concurrent.atomic.AtomicInteger;
public class PCB {
public void read (String [] args) {
BufferedReader inputStream = null;
try {
inputStream = new BufferedReader(new FileReader("processes1.txt"));
String l;
while ((l = inputStream.readLine()) != null) {
write(l);
}
}
finally {
if (inputStream != null) {
inputStream.close();
}
}
}
public void write(String table) {
char status;
String name;
int priority;
ArrayList<String> tokens = new ArrayList<String>();
Scanner tokenize = new Scanner(table);
while (tokenize.hasNext()) {
tokens.add(tokenize.next());
}
status = 'n';
name = tokens.get(0);
String priString = tokens.get(1);
priority = Integer.parseInt(priString);
AtomicInteger count = new AtomicInteger(0);
count.incrementAndGet();
int pid = count.get();
System.out.println("PID: " + pid);
}
}
我的眼珠子都快戳出来了.我遇到了三个错误:
I am about to poke out my eyeballs. I got three errors:
U:Senior YearCS451- Operating SystemsProject1 PCBPCB.java:24: unreported exception java.io.IOException; must be caught or declared to be thrown
inputStream.close();}
^
U:Senior YearCS451- Operating SystemsProject1 PCBPCB.java:15: unreported exception java.io.FileNotFoundException; must be caught or declared to be thrown
inputStream = new BufferedReader(new FileReader("processes1.txt"));
^
U:Senior YearCS451- Operating SystemsProject1 PCBPCB.java:18: unreported exception java.io.IOException; must be caught or declared to be thrown
while ((l = inputStream.readLine()) != null) {
^
我做错了什么?
推荐答案
当您在 Java 中使用 I/O 时,大多数时候您必须处理在读/写甚至关闭流时随时可能发生的 IOException.
When you work with I/O in Java most of the time you have to handle IOException which can occur any time when you read/write or even close the stream.
您必须将敏感块放入 try//catch 块中并在此处处理异常.
You have to put your sensitive block in a try//catch block and handle the exception here.
例如:
try{
// All your I/O operations
}
catch(IOException ioe){
//Handle exception here, most of the time you will just log it.
}
<小时>
资源:
- oracle.com - 课程:例外
这篇关于为什么我会得到“必须被抓住或被宣布被扔"?在我的节目上?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!