Java 逐字读取文件
我的项目中有一个输出文件,其中包含以下信息:Java 逐字读取文件,java,file,Java,File,我的项目中有一个输出文件,其中包含以下信息: <Keyword: begin > <Keyword: for > <Id: i > tokenArr = new ArrayList<String>(); BufferedReader input ; String line,value="",type=""; int index=2; char ch; try { input = new BufferedReader(ne
<Keyword: begin >
<Keyword: for >
<Id: i >
tokenArr = new ArrayList<String>();
BufferedReader input ;
String line,value="",type="";
int index=2;
char ch;
try
{
input = new BufferedReader(new FileReader(fileName));
System.out.println("File is Opened!");
while ((line = input.readLine())!=null)
{
ch = line.charAt(index);
while( ch !=' ')
{
value += ch;
index++;
ch = line.charAt(index);
}
索引是2,因为我不想要前2个字符。你能帮我一下吗?在内部while循环之后,你可能无法重置索引。此外,如果行中根本不包含空格字符,该怎么办?内部while循环只有在索引达到
line.length()
时才会结束,因此line.charAt()抛出StringIndexOutOfBoundsException
使用substring()方法代替逐字符处理:
您需要通过以下方式稍微修改while循环:
while ((line = input.readLine())!=null)
{
if (line.length() > 3 )//because you starting with index 2
{
ch = line.charAt(index);
while( ch !=' ')
{
value += ch;
index++;
ch = line.charAt(index);
index = 2; //reset index to 2
}
}
}
您应该首先调试每行的while循环。在那里写一个SOP,并检查它到底打印了什么。似乎有一行没有任何字符。
while((line = input.readLine()) != null) {
if(line.length() > 2) {
line = line.substring(2); //I don't want the first two chars
if(!line.contains(" ")) {
value += line + "\n";
// if value were a StringBuilder value.append(line).append('\n');
}
else {
value += line.substring(0, line.indexOf(" ")) + "\n";
// StringBuilder value.append(line.substring(0, line.indexOf(" ")).append('\n');
}
}
while ((line = input.readLine())!=null)
{
if (line.length() > 3 )//because you starting with index 2
{
ch = line.charAt(index);
while( ch !=' ')
{
value += ch;
index++;
ch = line.charAt(index);
index = 2; //reset index to 2
}
}
}