如何通过读取 .txt 文件分配变量并使其固定长度?
How do I assign variables from reading .txt files and making it a fixed length?
我正在尝试读取一个非固定长度的 .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
这是我对您的问题的解决方案。也许这就是您一直在寻找的。
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
public class FileData {
public static void main (String[] args) {
FileData fileData = new FileData();
String file = "C:\Development\sandbox\test.txt";
StringBuffer contents = new StringBuffer();
String headline = "(Institution)\t\t\t\t\t(V_25)\t(V_75)\t(M_25)\t(M_75)\t(sub)\t(enrol)\n";
// insert the headline
contents.append(headline);
// read the file and convert it. At this point you've got a list of maps,
// each map containing the values of 1 line addressed by the belonging key
ArrayList<HashMap<String, String>> fileContent = fileData.readData(file);
// now you're going to assemble your output-table
for(HashMap<String, String> lineContent : fileContent){
// Add the institution, but adjust the string size before
contents.append(fileData.stringSizer(lineContent.get("Institution")));
// Add a tab and the next value
contents.append("\t");
contents.append(lineContent.get("V_25"));
// Add a tab and the next value
contents.append("\t");
contents.append(lineContent.get("V_75"));
// Add a tab and the next value
contents.append("\t");
contents.append(lineContent.get("M_25"));
// Add a tab and the next value
contents.append("\t");
contents.append(lineContent.get("M_75"));
// Add a tab and the next value
contents.append("\t");
contents.append(lineContent.get("Submit"));
// Add a tab and the next value
contents.append("\t");
contents.append(lineContent.get("Enrollment"));
// add a new line the word "blank" and another new line
contents.append("\nblank\n");
}
// That's it. Here's your well formed output string.
System.out.println(contents.toString());
}
private ArrayList<HashMap<String, String>> readData(String fileName){
String inputLine = new String();
String[] lineElements;
ArrayList<HashMap<String, String>> fileContent = new ArrayList<>();
HashMap<String, String> lineContent;
// try with resources
try(BufferedReader LineIn = new BufferedReader(new FileReader(fileName))) {
while ((inputLine = LineIn.readLine()) != null){
// every new line gets its own map
lineContent = new HashMap<>();
// split the current line up by comma
lineElements = inputLine.split(",");
// put each value indexed by its key into the map
lineContent.put("Institution", lineElements[0]);
lineContent.put("V_25", lineElements[1]);
lineContent.put("V_75", lineElements[2]);
lineContent.put("M_25", lineElements[3]);
lineContent.put("M_75", lineElements[4]);
lineContent.put("Submit", lineElements[5]);
lineContent.put("Enrollment", lineElements[6]);
// add the map to your list
fileContent.add(lineContent);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
// everything went well. Return the list.
return fileContent;
}
private String stringSizer(String value){
// if value is longer than 40 letters return the trimmed version immediately
if (value.length() > 40) {
return value.substring(0, 40);
}
// if values length is lower than 40 letters, fill in the blanks with spaces
if (value.length() < 40) {
return String.format("%-40s", value);
}
// value is exactly 40 letters long
return value;
}
}
在我看来你应该使用一个数组,数组我的意思是一个 java.util.ArrayList or java.util.List 接口,例如:
List<String> list = new ArrayList<>();
A List 可以很容易地添加和增长(以及许多其他东西),而不需要像 [=14 那样将其初始化为特定大小=] 数组。由于我们不知道数据文件 (input.txt) 中可能包含多少行数据,因此使用 List Interface 是一个非常好的方法,例如:
需要进口:
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
执行任务的代码:
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader("/Users/GANGSTATOP/Documents/workspace/DBTruncate/src/input.txt"));
String text;
List<String> list = new ArrayList<>(); // To hold file data
int longestLength = 0; // Longest University name length
while ((text = reader.readLine()) != null) {
// Add text line to our list array
list.add(text);
// Get the longest length of University names
// for display purposes later on.
if (!text.isEmpty()) {
if (longestLength < text.indexOf(",")) { longestLength = text.indexOf(","); }
}
}
// Sort the List
Collections.sort(list);
// Create & display the Header Line...
String sv = "Institution";
while (sv.length() < longestLength) { sv+= " "; }
sv+= " v_25 v_75 m_25 m_75 Sub Enroll";
System.out.println(sv);
// Create & display the Header Underline...
String ul = "=";
while (ul.length() < (sv.length())) { ul+= "="; }
System.out.println(ul + "\n");
// Iterate through & display the Data...
for (int i = 0; i < list.size(); i++) {
// Pull out the University name from List
// element and place into variable un
String un = list.get(i).substring(0, list.get(i).indexOf(","));
// Right Pad un with spaces to match longest
// University name. This is so everthing will
// tab across console window properly.
while (un.length() < longestLength) { un+= " "; }
// Pull out the university data and convert the
// comma delimiters to tabs then place a newline
// tag at end of line so as to display a blank one.
String data = list.get(i).substring(list.get(i).indexOf(",")+1).replace(",", "\t") + "\n";
//Display the acquired data...
System.out.println(un + "\t" + data);
}
}
catch (FileNotFoundException e) { e.printStackTrace(); }
catch (IOException e) { e.printStackTrace(); }
finally {
try { if (reader != null) { reader.close(); } }
catch (IOException e) { e.printStackTrace(); }
}
一旦所有文件数据都包含在列表中,就不再需要硬件访问,列表中的所有数据都可以轻松检索、排序,并随您操作除非数据文件非常大并且您想在数据块中工作,否则当然可以。
这是我的建议:
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");
}
}
这将是我的初稿。
我正在尝试读取一个非固定长度的 .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
这是我对您的问题的解决方案。也许这就是您一直在寻找的。
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
public class FileData {
public static void main (String[] args) {
FileData fileData = new FileData();
String file = "C:\Development\sandbox\test.txt";
StringBuffer contents = new StringBuffer();
String headline = "(Institution)\t\t\t\t\t(V_25)\t(V_75)\t(M_25)\t(M_75)\t(sub)\t(enrol)\n";
// insert the headline
contents.append(headline);
// read the file and convert it. At this point you've got a list of maps,
// each map containing the values of 1 line addressed by the belonging key
ArrayList<HashMap<String, String>> fileContent = fileData.readData(file);
// now you're going to assemble your output-table
for(HashMap<String, String> lineContent : fileContent){
// Add the institution, but adjust the string size before
contents.append(fileData.stringSizer(lineContent.get("Institution")));
// Add a tab and the next value
contents.append("\t");
contents.append(lineContent.get("V_25"));
// Add a tab and the next value
contents.append("\t");
contents.append(lineContent.get("V_75"));
// Add a tab and the next value
contents.append("\t");
contents.append(lineContent.get("M_25"));
// Add a tab and the next value
contents.append("\t");
contents.append(lineContent.get("M_75"));
// Add a tab and the next value
contents.append("\t");
contents.append(lineContent.get("Submit"));
// Add a tab and the next value
contents.append("\t");
contents.append(lineContent.get("Enrollment"));
// add a new line the word "blank" and another new line
contents.append("\nblank\n");
}
// That's it. Here's your well formed output string.
System.out.println(contents.toString());
}
private ArrayList<HashMap<String, String>> readData(String fileName){
String inputLine = new String();
String[] lineElements;
ArrayList<HashMap<String, String>> fileContent = new ArrayList<>();
HashMap<String, String> lineContent;
// try with resources
try(BufferedReader LineIn = new BufferedReader(new FileReader(fileName))) {
while ((inputLine = LineIn.readLine()) != null){
// every new line gets its own map
lineContent = new HashMap<>();
// split the current line up by comma
lineElements = inputLine.split(",");
// put each value indexed by its key into the map
lineContent.put("Institution", lineElements[0]);
lineContent.put("V_25", lineElements[1]);
lineContent.put("V_75", lineElements[2]);
lineContent.put("M_25", lineElements[3]);
lineContent.put("M_75", lineElements[4]);
lineContent.put("Submit", lineElements[5]);
lineContent.put("Enrollment", lineElements[6]);
// add the map to your list
fileContent.add(lineContent);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
// everything went well. Return the list.
return fileContent;
}
private String stringSizer(String value){
// if value is longer than 40 letters return the trimmed version immediately
if (value.length() > 40) {
return value.substring(0, 40);
}
// if values length is lower than 40 letters, fill in the blanks with spaces
if (value.length() < 40) {
return String.format("%-40s", value);
}
// value is exactly 40 letters long
return value;
}
}
在我看来你应该使用一个数组,数组我的意思是一个 java.util.ArrayList or java.util.List 接口,例如:
List<String> list = new ArrayList<>();
A List 可以很容易地添加和增长(以及许多其他东西),而不需要像 [=14 那样将其初始化为特定大小=] 数组。由于我们不知道数据文件 (input.txt) 中可能包含多少行数据,因此使用 List Interface 是一个非常好的方法,例如:
需要进口:
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
执行任务的代码:
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader("/Users/GANGSTATOP/Documents/workspace/DBTruncate/src/input.txt"));
String text;
List<String> list = new ArrayList<>(); // To hold file data
int longestLength = 0; // Longest University name length
while ((text = reader.readLine()) != null) {
// Add text line to our list array
list.add(text);
// Get the longest length of University names
// for display purposes later on.
if (!text.isEmpty()) {
if (longestLength < text.indexOf(",")) { longestLength = text.indexOf(","); }
}
}
// Sort the List
Collections.sort(list);
// Create & display the Header Line...
String sv = "Institution";
while (sv.length() < longestLength) { sv+= " "; }
sv+= " v_25 v_75 m_25 m_75 Sub Enroll";
System.out.println(sv);
// Create & display the Header Underline...
String ul = "=";
while (ul.length() < (sv.length())) { ul+= "="; }
System.out.println(ul + "\n");
// Iterate through & display the Data...
for (int i = 0; i < list.size(); i++) {
// Pull out the University name from List
// element and place into variable un
String un = list.get(i).substring(0, list.get(i).indexOf(","));
// Right Pad un with spaces to match longest
// University name. This is so everthing will
// tab across console window properly.
while (un.length() < longestLength) { un+= " "; }
// Pull out the university data and convert the
// comma delimiters to tabs then place a newline
// tag at end of line so as to display a blank one.
String data = list.get(i).substring(list.get(i).indexOf(",")+1).replace(",", "\t") + "\n";
//Display the acquired data...
System.out.println(un + "\t" + data);
}
}
catch (FileNotFoundException e) { e.printStackTrace(); }
catch (IOException e) { e.printStackTrace(); }
finally {
try { if (reader != null) { reader.close(); } }
catch (IOException e) { e.printStackTrace(); }
}
一旦所有文件数据都包含在列表中,就不再需要硬件访问,列表中的所有数据都可以轻松检索、排序,并随您操作除非数据文件非常大并且您想在数据块中工作,否则当然可以。
这是我的建议:
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");
}
}
这将是我的初稿。