如何从读取.txt文件中分配变量并使其成为固定长度?

时间:2017-01-28 18:50:40

标签: java arraylist string-formatting

我正在尝试读取不是固定长度的.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

3 个答案:

答案 0 :(得分:0)

这是我解决您问题的方法。也许这就是你一直在寻找的东西。

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;
  }
}

答案 1 :(得分:0)

在我看来,你应该使用数组和数组我的意思是java.util.ArrayListjava.util.List接口,例如:

List<String> list = new ArrayList<>();

列表可以很容易地添加到(并在其他许多内容中),而无需将其初始化为特定大小,就像让我们说{{3}一样数组。由于我们不知道数据文件(input.txt)中可能包含多少行数据,因此使用列表接口是一种非常好的方法,例如:

必需的进口:

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(); }
}

一旦所有文件数据都包含在List中,就不再需要硬件访问,并且可以轻松检索List中的所有数据,排序,并按照您认为合适的方式进行操作,除非当然如果数据文件非常大并且您想要使用Data Chunks。

答案 2 :(得分:0)

这是我的建议:

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");
    }
}

这将是我的第一个答案草案。