我想读取一个包含一些数字的文件,即 Account.txt
并希望将每一行保存到数组的字符串中。
前任。该文件有 3 行 123\n234\n456
。字符串数组 a 有 3 个大小,第一个数组应有 123,第二个数组应有 234,第三个数组应有 456。
但它不起作用。
提前致谢。
package javaapplication10;
import java.util.Scanner;
import java.io.*;
public class JavaApplication10
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
String temp = " ";
FileWriter fw = null;
FileReader fr = null;
int a=0;
while(true)
{
System.out.println("1) Input new ");
System.out.println("2) display ");
System.out.println("3) Exit");
System.out.print(" Enter your choice : ");
int choice = input.nextInt();
switch(choice)
{
case 1: System.out.println(" Enter new Account number : ");
temp = input.next();
try
{
fw = new FileWriter("Account.txt",true );
fw.write(temp);
fw.write(System.getProperty( "line.separator" ));
fw.flush();
}
catch(IOException ex)
{
ex.printStackTrace();
}
catch(Exception ex)
{
ex.printStackTrace();
}
finally
{
if(fw!=null)
{
try
{
fw.close();
}
catch(IOException ex)
{
ex.printStackTrace();
}
}
}
break;
case 2: try
{
fr = new FileReader("Account.txt");
int i = 0;
int line =0;
while((i = fr.read()) != -1)
{
if(i == '\n')
line++;
}
String s[] = new String[line];
a=0;
i=0;
System.out.println("2");
for(int j=0; j<line;j++)
{
while((i = fr.read())!=10)
{
if(i!=-1)
{
System.out.println(String.valueOf(i));
s[j] = s[j].concat(String.valueOf(i));
}
else
break;
}
System.out.println(s[j]);
}
}
catch(FileNotFoundException ex)
{
ex.printStackTrace();
}
catch(IOException ex)
{
ex.printStackTrace();
}
finally
{
if(fr!=null)
{
try
{
fr.close();
}
catch(IOException ex)
{
ex.printStackTrace();
}
fr = null;
}
}
break;
case 3: System.exit(0);
default: System.out.println(" Wrong Choice !!!");
}
}
}
}
最佳答案
您尝试读取文件两次。第一个循环之后:
while((i = fr.read()) != -1)
{
if(i == '\n')
line++;
}
您的文件指针位于文件末尾。因此,在第二个循环中,您没有更多内容可阅读。
关于java - 读取文件时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29554321/