我正在尝试读取不是固定长度的.txt文件,并将其转换为一定的固定长度。我尝试在while循环中为读取为split()的每一行使用一个数组,但是它一直给我奇怪的格式,所以我把它取出来了!我希望该机构的格式设置为40个字符长度,v_25-子变量的固定长度为3,而注册变量的格式设置为4!请帮忙!
import java.io.*;
public class FileData {
public static void main (String[] args) {
File file = new File("test.txt");
StringBuffer contents = new StringBuffer();
BufferedReader reader = null;
// int counter = 0;
String institution = null;
String V_25 = null;
String V_75 = null;
String M_25 = null;
String M_75 = null;
String Submit = null;
String Enrollment = null;
try {
reader = new BufferedReader(new FileReader("/Users/GANGSTATOP/Documents/workspace/DBTruncate/src/input.txt"));
String text = null;
// repeat until all lines is read
while ((text = reader.readLine()) != null) {
contents.append(text.replaceAll(",", " ")).append("\nblank\n");
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (reader != null) {
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
// show file contents here
System.out.println(contents.toString());
}
}
最初读取文件:
Adelphi University,500,600,510,620,715,7610
Alabama State University,380,470,380,480,272,5519
我如何使它看起来像:
(institution) (v_25) (v_75) (m_25) (m_75) (sub) (enroll)
Adelphi University 500 600 510 620 715 7610
blank
Alabama State University 380 470 380 480 272 5519
blank
这是我的建议:
BufferedReader reader = null;
List<String> list = new ArrayList<>();
try {
reader = new BufferedReader(new FileReader("input.txt"));
String temp;
while ((temp= reader.readLine()) != null) {
list.add(temp);
}
}
catch (FileNotFoundException e) { e.printStackTrace(); }
catch (IOException e) { e.printStackTrace(); }
finally {
try { if (reader != null) { reader.close(); } }
catch (IOException e) { e.printStackTrace(); }
}
System.out.println(String.format("%12s%12s%12s%12s%12s%12s\n\n",
"v_25", "v_72", "m_25", "m_75", "Sub", "Enroll"));
for(int i= 0;i < list.size();i++){
String temp2[] = list.split(",");
if(temp2.length == 6){
System.out.println(String.format("%12s%12s%12s%12s%12s%12s\n\n", temp2[0], temp2[1],temp2[2],temp2[3],temp2[4],temp2[5]);
}
else{
System.out.println("Error");
}
}
那将是我的初稿。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句