我正在尝试读取文件并将每个读入的字符复制到字符数组中,并将其打印在JAVA中
问题描述:
我试图读取文件并复制每个字符,因为它读取到字符数组中然后将其打印出来。 输出仅显示从文件中读取的最后一个字符。我正在尝试读取文件并将每个读入的字符复制到字符数组中,并将其打印在JAVA中
文本文件:“kgdsfhgsdfbsdafj B于屏幕
输出: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++;
}
它的工作谢谢哥们 – 2014-11-22 16:15:17