我的java程序应该读入并显示用户在提示时输入的.txt文件,将文件中的整数转换为输出.dat文件,然后读入.dat文件并再次显示数字。当我运行我的程序时,它显示文件的内容,并创建.dat文件,但不再读取它。我的代码如下。我需要做什么?
public class InputFile
{
public static void main(String [] args)
{
BufferedReader inputStream = null;
System.out.print("Enter file name (with .txt extension): ");
Scanner keys = new Scanner(System.in);
String inFileName = keys.next();
try
{
inputStream = new BufferedReader (new FileReader(inFileName));
System.out.println("The file " + inFileName + " contains the following lines:");
String inFileString = inputStream.readLine();
while(inFileString != null)
{
System.out.println(inFileString);
inFileString = inputStream.readLine();
}
inputStream.close();
}
catch(FileNotFoundException e)
{
System.out.println(inFileName + " not found! Try Again.");
}
catch(IOException e)
{
System.out.println(e.getMessage());
}
String fileName = "numbers.dat";
try
{
ObjectOutputStream outputStream = new ObjectOutputStream(new FileOutputStream(fileName));
int anInt = 0;
while(anInt >=0);
{
anInt = Integer.parseInt(inputStream.readLine());
outputStream.writeInt(anInt);
}
outputStream.close();
}
catch(FileNotFoundException e)
{
System.out.println("Problem opening file.");
}
catch(IOException e)
{
System.out.println("Problem with output to the file.");
}
try
{
ObjectInputStream inputStream2 = new ObjectInputStream(new FileInputStream(fileName));
System.out.println("The file being read yields:");
int anInteger = inputStream2.readInt();
while(anInteger >= 0)
{
System.out.println(anInteger);
anInteger = inputStream2.readInt();
}
inputStream2.close();
}
catch(FileNotFoundException e)
{
System.out.println("Problem with opening the file.");
}
catch(EOFException e)
{
System.out.println("Problem reading the file.");
}
catch(IOException e)
{
System.out.println("There was a problem reading the file.");
}
}
}
答案 0 :(得分:2)
有一种错误(或者至少我认为这是一种错误的类型)很难发现会使你的第二个循环变得无限。
(...)
try
{
ObjectOutputStream outputStream = new ObjectOutputStream(new FileOutputStream(fileName));
int anInt = 0;
while(anInt >=0); <=====
{
anInt = Integer.parseInt(inputStream.readLine());
outputStream.writeInt(anInt);
}
outputStream.close();
}
删除此';'过了一会儿,我想它会正常运行。
答案 1 :(得分:1)
您没有写入输出流,因为到那时inputStream已经耗尽并且已关闭。
创建一个集合来存储第一个文件中的元素。
String inFileName = keys.next();
Collection<String> lines = new ArrayList<String>();
...
System.out.println(inFileString);
lines.add(inFileString);
...
for(String line : lines){
...
outputStream.write(Integer.parseInt(line));
...
}