2017-01-28 1 views
1

Я пытаюсь прочитать .txt-файл, который не является фиксированной длиной и преобразовать его в определенную фиксированную длину. Я попытался использовать массив в цикле while для каждой строки, которая читается как split(), но она все время давала мне странные форматы, поэтому я взял ее! Я хотел, чтобы учреждение было отформатировано для 40 длин символов, v_25 - вспомогательные переменные - фиксированная длина 3, а переменная регистрации должна быть установлена ​​равной 4! Пожалуйста помоги!Как назначить переменные из чтения TXT-файлов и сделать их фиксированной?

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 
+0

«Это не работало, поэтому я взял его» ... Не вынимайте его. Покажите нам, что вы пробовали. – nhouser9

ответ

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

Это будет мой первый проект ответа.

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

На мой взгляд, вы должны использовать массив и массив, я имею в виду интерфейс java.util.ArrayList или java.util.List, например:

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

Список могут быть легко добавлены и расти (среди многих другие вещи) без необходимости инициализировать его до определенного размера, как это было бы, например, с массивом String[]. Так как мы не знаем, сколько строк данных могут содержаться в использовании файла данных (input.txt) из списка Интерфейс это действительно хороший способ пойти, например:

Необходимые Imports:

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

После того, как все данные файла содержится в списке, доступ к оборудованию больше не требуется, и все данные в списке могут быть легко извлечены, сортировали, и манипулировать, как вам кажется, если, конечно, если файл данных достаточно велик и вы хотите работать в Data Chunks.

Смежные вопросы