我试图读取一个文件,并将读取的每个字符复制到一个字符数组中,然后用JAVA打印它

我试图读取一个文件,并将读取的每个字符复制到一个字符数组中,然后用JAVA打印它,java,Java,我正在尝试读取一个文件,并将读取到的每个字符复制到一个字符数组中,然后打印它。 输出仅显示从文件中读取的最后一个字符 文件中的文本:kgdsfhgsdfbsdafjb 屏幕上的输出:b 如果有什么问题,请提出建议 我的代码: char pt[] = new char[count]; //File is opened again and this time passed into the plain text array FileInputStream f = new FileInputStr

我正在尝试读取一个文件,并将读取到的每个字符复制到一个字符数组中,然后打印它。 输出仅显示从文件中读取的最后一个字符

文件中的文本:kgdsfhgsdfbsdafjb

屏幕上的输出:b

如果有什么问题,请提出建议

我的代码:

char pt[] = new char[count];

//File is opened again and this time passed into the plain text array 
FileInputStream f = new FileInputStream("/Documents/file1.txt") ;

int s ;

while((s = f.read()) != -1 )            
{
    int ind = 0;

    pt[ind] = (char) s ;
    ind ++ ;                
}

for( int var = 0 ; var < pt.length ; var++)         
{
    System.out.print(pt[var]) ;
} 

f.close();
int ind=0;应该在循环之前

int ind = 0;
while((s = f.read()) != -1 )
{    
    pt[ind] = (char) s ;
    ind ++ ;

}
现在,您将每个字符读入pt[0],因此最后只剩下最后一个字符。

从循环中取出int ind=0行。
按照现在的方式,每次迭代都会将索引重置为零。

将代码更改为以下内容:

int ind = 0;

while ((s = f.read()) != -1) {

    pt[ind] = (char) s;
    ind++;

}

它仍然不起作用,会有越界异常

错误在于线路

        pt[ind] = (char) s;
可能有。这取决于计数。也许你应该先描述一下为什么会有ArrayIndexOutOfBoundsException。