Java 读取文本文件中的每个字符
我试图读入文本文件中的每个字符(制表符、新行)。我在阅读所有这些方面都有困难。我当前的方法读取中的选项卡,但不读取新行。代码如下:Java 读取文本文件中的每个字符,java,text,bufferedreader,filereader,Java,Text,Bufferedreader,Filereader,我试图读入文本文件中的每个字符(制表符、新行)。我在阅读所有这些方面都有困难。我当前的方法读取中的选项卡,但不读取新行。代码如下: //reads each character in as an integer value returns an arraylist with each value public static ArrayList<Integer> readFile(String file) { FileReader fr = null;
//reads each character in as an integer value returns an arraylist with each value
public static ArrayList<Integer> readFile(String file) {
FileReader fr = null;
ArrayList<Integer> chars = new ArrayList<Integer>(); //to be returned containing all commands in the file
try {
fr = new FileReader(file);
BufferedReader br = new BufferedReader(fr);
int tempChar = ' ';
String tempLine = "";
while ((tempLine = br.readLine()) != null) {
for (int i = 0; i < tempLine.length(); i++) {
int tempIntValue = tempLine.charAt(i);
chars.add(tempIntValue);
}
}
fr.close();
br.close();
} catch (FileNotFoundException e) {
System.out.println("Missing file");
System.exit(0);
} catch (IOException e) {
System.out.println("Empty file");
System.exit(0);
}
return chars;
}
//以整数值形式读取中的每个字符,并返回包含每个值的arraylist
公共静态ArrayList读取文件(字符串文件){
FileReader fr=null;
ArrayList chars=new ArrayList();//返回,包含文件中的所有命令
试一试{
fr=新文件读取器(文件);
BufferedReader br=新的BufferedReader(fr);
int tempChar='';
字符串tempLine=“”;
而((tempLine=br.readLine())!=null){
对于(int i=0;i
我最初使用read()方法而不是readLine(),但这也有同样的问题。我将字符表示为int。非常感谢您的帮助 我建议您使用、List
和菱形操作符
,并使用该方法读取每个字符
公共静态列表读取文件(字符串文件){
列表字符=新的ArrayList();
try(FileReader fr=新的FileReader(file);
BufferedReader br=新的BufferedReader(fr);){
int-ch;
而((ch=br.read())!=-1){
添加字符(ch);
}
}catch(filenotfounde异常){
System.out.println(“缺少文件”);
系统出口(0);
}捕获(IOE异常){
System.out.println(“空文件”);
系统出口(0);
}
返回字符;
}
Javadoc记录了您没有得到行尾的原因,其中部分(强调部分)提到
包含行内容的字符串,不包括任何行终止字符
为什么不在知道新行将存在(即,当前行已完成)时手动添加新行呢?
read()
也有同样的问题,这是不可行的。为什么不使用read(),然后询问其他问题?
public static List<Integer> readFile(String file) {
List<Integer> chars = new ArrayList<>();
try (FileReader fr = new FileReader(file);
BufferedReader br = new BufferedReader(fr);) {
int ch;
while ((ch = br.read()) != -1) {
chars.add(ch);
}
} catch (FileNotFoundException e) {
System.out.println("Missing file");
System.exit(0);
} catch (IOException e) {
System.out.println("Empty file");
System.exit(0);
}
return chars;
}