我有一个字符串数组toFile[]
,我尝试写入文本文件。在测试过程中,我被提醒,如果刺痛达到窗口边界,记事本不会将字符串包装到下一行。作为一名完美主义者,我想将字符串拆分为长度为250个字符的子字符串,并将每个字符串写入文件,在每个子字符串之后打破新行。需要帮助将字符串写入文本文件中的多行
测试时,我遇到的问题似乎无法解决,是因为我的程序会一次运行循环,然后失败并显示错误。
输出和错误的一个例子:
toFile[2].length = 2432
temp.length = 250
split = 250
iLength = 2182
temp.length = 0
split = 500
iLength = 1932
java.lang.StringIndexOutOfBoundsException: String index out of range: -250
我的代码:
System.out.println("toFile[2].length = "+Integer.toString(toFile[2].length()));
System.out.println("");
if(toFile[2].length()>250){
int iLength=toFile[2].length(), split = 0;
while(iLength>250){
String temp = toFile[2];
temp = temp.substring(split, 250);
System.out.println("temp.length = "+Integer.toString(temp.length()));
bw.write(temp);bw.newLine();
split=split+250;
System.out.println("split = "+Integer.toString(split));
iLength=iLength-250;
System.out.println("iLength = "+Integer.toString(iLength));
System.out.println("");
}
bw.write(toFile[2].substring(split));
}else{bw.write(toFile[2]);bw.newLine();}
bw.newLine();
我也试着穿过整个串运行,但仍然只写入字符串到一个这个while循环line:
int iLength=toFile[2].length(), start = 0;
String temp = toFile[2];
while(iLength>250){
bw.write(temp,start,250);
start=start+250;
System.out.println("start = "+Integer.toString(start));
iLength=iLength-250;
System.out.println("iLength = "+Integer.toString(iLength));
System.out.println("");
}
你需要一个嵌套循环(所以总共两个循环)。外层循环遍历数组中的所有字符串toFile。内循环计算字符数为250. – markspace 2014-09-11 01:37:49
@markspace数组只包含9个字符串。在这9个,我只需要检查一些长度。 – TehNoiseBomb 2014-09-11 01:57:28
你仍然需要两个循环。尝试制作一种除了将字符串分割为所需长度以外别无它法的方法。它会帮助你将问题分解成更小的问题。然后调用该方法来检查需要检查的字符串。 – markspace 2014-09-11 03:12:03