如何按顺序读取文件?
public static void main(String[] args){
String fichier ="E:\\fichiers\\test.txt";
int tab[] = {2, 2, 20, 8, 20, 8, 4, 3, 7, 3, 3, 3, 18, 139};
String tabS[] = new String[14];
for(int i=0; i<tab.length; i++){
char cbuf[] = new char[tab[i]];
try {
InputStream ips = new FileInputStream(fichier);
InputStreamReader ipsr = new InputStreamReader(ips);
BufferedReader br = new BufferedReader(ipsr);
br.read(cbuf, 0, tab[i]);
tabS[i] = new String(cbuf);
System.out.println(tabS[i]);
} catch (Exception e){
System.out.println(e.toString());
}
}
}
我的文件内容只有这一行:
BOUUUUUUUUUUUUUUUUUUUUUU!
当我运行 readMe 方法时,我得到了这个:
BO BO BOUUUUUUUUUUUUUUUUUU BOUUUUUU BOUUUUUUUUUUUUUUUUUU BOUUUUUU BOUU BOU BOUUUUU BOU BOU BOU BOUUUUUUUUUUUUUUUU BOUUUUUUUUUUUUUUUUUUUUUU!
这里的问题是,每当他开始阅读文件时,它就开始位于0。
请帮忙吗?
答案 0 :(得分:2)
在我看来,你需要在创建流之后在try / catch中移动for循环。
public static void main(String[] args){
String fichier ="E:\\fichiers\\test.txt";
int tab[] = {2, 2, 20, 8, 20, 8, 4, 3, 7, 3, 3, 3, 18, 139};
String tabS[] = new String[14];
try {
InputStream ips = new FileInputStream(fichier);
InputStreamReader ipsr = new InputStreamReader(ips);
BufferedReader br = new BufferedReader(ipsr);
for(int i=0; i<tab.length; i++){
char cbuf[] = new char[tab[i]];
br.read(cbuf, 0, tab[i]);
tabS[i] = new String(cbuf);
System.out.println(tabS[i]);
}
} catch (Exception e){
System.out.println(e.toString());
}
}
答案 1 :(得分:2)
看你有:
int tab[] = {2, 2, 20, 8, 20, 8, 4, 3, 7, 3, 3, 3, 18, 139};
您的输出是:
BO // length 2
BO // length 2
BOUUUUUUUUUUUUUUUUUU // length 20
BOUUUUUU // length 8
BOUUUUUUUUUUUUUUUUUU
BOUUUUUU
BOUU
BOU
BOUUUUU
BOU
BOU
BOU
BOUUUUUUUUUUUUUUUU
BOUUUUUUUUUUUUUUUUUUUUUU!
这是有道理的:
br.read(cbuf, 0, tab[i]);
tabS[i] = new String(cbuf);
System.out.println(tabS[i]);
它在每次迭代中从第0位开始,因为你有:
InputStream ips = new FileInputStream(fichier);
InputStreamReader ipsr = new InputStreamReader(ips);
BufferedReader br = new BufferedReader(ipsr);
在for
循环内。只需将其从循环中删除即可解决问题:
try
{
InputStream ips = new FileInputStream(fichier);
InputStreamReader ipsr = new InputStreamReader(ips);
BufferedReader br = new BufferedReader(ipsr);
for(int i=0; i<tab.length; i++)
{
char cbuf[] = new char[tab[i]];
br.read(cbuf, 0, tab[i]);
tabS[i] = new String(cbuf);
System.out.println(tabS[i]);
}
}
catch (Exception e)
{
System.out.println(e.toString());
}