2015-06-25 3 views
1

Я хочу прочитать данные от Host.txt и от Instance.txt, я могу прочитать данные, но я не уверен, как это можно связать!Как читать данные из двух текстовых файлов и связывать данные?

Вот Хост файл:

Host ID  Number of Slots  Data Centre 
=======  ===============  ============ 
2,     4,     0 
5,     4,     0 
7,     3,     0 
9,     3,     1 
3,     3,     1 
10,     2,     2 
6,     4,     2 
8,     2,     2 

Вот Instance файл:

Instance ID   Customer  Host ID 
===========   =========  ======= 
1,       8,    2 
2,       8,    2 
3,       8,    2 
4,       8,    7 
5,      15,    7 
6,      16,    9 
7,      13,    9 
8,       9,    3 
9,      13,    3 
10,      16,    5 
11,      15,    8 
12,      8,    6 
13,      16,    8 
14,      9,    9 
15,      9,    7 

Вот код, который я использую для чтения файлов:

public class CloudStructure { 

    public static void main(String[] args) { 

     readHost("C:\\tmp\\HostState.txt"); 
     readInstance("C:\\tmp\\InstanceState.txt"); 
    } 

    public static void readHost(String filePath) 
    { 
     String line = ""; 

     ArrayList<String> host = new ArrayList<String>(); 
     ArrayList<String> slot = new ArrayList<String>(); 
     ArrayList<String> centre = new ArrayList<String>(); 

     CloudStructureData getHostTxtData = new CloudStructureData(); 

     FileReader fr; 
     BufferedReader br; 

     String[] HostID = null; 
     String[] Slots = null; 
     String[] DataCentre = null; 

      try { 
       fr = new FileReader(filePath); 
       br = new BufferedReader(fr); 

       while((line = br.readLine()) != null) 
       { 
        HostID = line.split(","); 
        Slots = line.split(","); 
        DataCentre = line.split(",");     

        host.add(HostID[0]); 
        slot.add(Slots[1]);   
        centre.add(DataCentre[2]); 
       } 
       } 
       catch(FileNotFoundException fN) { 
       fN.printStackTrace(); 
       } 
       catch(IOException e) { 
       System.out.println(e); 
       } 

     getHostTxtData.setHostID(host); 
     getHostTxtData.setSlot(slot); 
     getHostTxtData.setCentre(centre); 

     System.out.println("Host File"); 
     System.out.println("============="); 
     System.out.println("Hosts:  " + getHostTxtData.getHostID()); 
     System.out.println("Slots:  " + getHostTxtData.getSlot()); 
     System.out.println("DataCentre: " + getHostTxtData.getCentre()); 
    } 

    public static void readInstance(String filePath) 
    { 
     String line = ""; 

     ArrayList<String> instance = new ArrayList<String>(); 
     ArrayList<String> customer = new ArrayList<String>(); 
     ArrayList<String> host = new ArrayList<String>(); 

     CloudStructureData getHostTxtData = new CloudStructureData(); 

     FileReader fr; 
     BufferedReader br; 

     String[] InstanceId = null; 
     String[] CustId = null; 
     String[] HostId = null; 

      try { 
       fr = new FileReader(filePath); 
       br = new BufferedReader(fr); 

       while((line = br.readLine()) != null) 
       { 
        InstanceId = line.split(","); 
        CustId = line.split(","); 
        HostId = line.split(",");     

        instance.add(InstanceId[0]); 
        customer.add(CustId[1]);   
        host.add(HostId[2]); 
       } 
       } 
       catch(FileNotFoundException fN) { 
       fN.printStackTrace(); 
       } 
       catch(IOException e) { 
       System.out.println(e); 
       } 

     getHostTxtData.setInstance(instance); 
     getHostTxtData.setCust(customer); 
     getHostTxtData.setHostInst(host); 

     System.out.println(); 
     System.out.println("Instance File"); 
     System.out.println("============="); 
     System.out.println("Instance: " + getHostTxtData.getIntstanceID()); 
     System.out.println("Customer: " + getHostTxtData.getCustomer()); 
     System.out.println("Host:  " + getHostTxtData.getHostInst()); 
    }  
} 

Мой другой класс:

package cloud; 

import java.util.ArrayList; 

public class CloudStructureData { 

    private ArrayList<String> sHostID; 
    private ArrayList<String> sSlot; 
    private ArrayList<String> sCentre; 

    private ArrayList<String> sInstanceID; 
    private ArrayList<String> sCust; 
    private ArrayList<String> sHostInst; 

    CloudStructureData(){ 
     sHostID = new ArrayList<String>(); 
     sSlot = new ArrayList<String>(); 
     sCentre = new ArrayList<String>(); 

     sInstanceID = new ArrayList<String>(); 
     sCust = new ArrayList<String>(); 
     sHostInst = new ArrayList<String>();   
    } 

    // Get Statements Host 
    public ArrayList<String> getHostID(){ 
     return sHostID; 
    } 

    public ArrayList<String> getSlot(){ 
     return sSlot; 
    } 

    public ArrayList<String> getCentre(){ 
     return sCentre; 
    } 

    // Get Statements Instance 
    public ArrayList<String> getIntstanceID(){ 
     return sInstanceID; 
    } 

    public ArrayList<String> getCustomer(){ 
     return sCust; 
    } 

    public ArrayList<String> getHostInst(){ 
     return sHostInst; 
    }  

    //Set Statements Host 
    public void setSlot(ArrayList<String> Slot){ 
     sSlot = Slot; 
    } 

    public void setCentre(ArrayList<String> Centre){ 
     sCentre = Centre; 
    } 

    public void setHostID(ArrayList<String> HostID) { 
     sHostID = HostID; 
    } 

    //Set Statements Instance 
    public void setInstance(ArrayList<String> InstanceID){ 
     sInstanceID = InstanceID; 
    } 

    public void setCust(ArrayList<String> Cust){ 
     sCust = Cust; 
    } 

    public void setHostInst(ArrayList<String> HostInst) { 
     sHostInst = HostInst; 
    } 

} 

Вот результат моей программы:

Host File 
============= 
Hosts:  [2, 5, 7, 9, 3, 10, 6, 8] 
Slots:  [4, 4, 3, 3, 3, 2, 4, 2] 
DataCentre: [0 , 0 , 0 , 1, 1, 2, 2, 2] 

Instance File 
============= 
Instance: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15] 
Customer: [8, 8, 8, 8, 15, 16, 13, 9, 13, 16, 15, 8, 16, 9, 9] 
Host:  [2, 2, 2, 7, 7, 9, 9, 3, 3, 5, 8, 6, 8, 9, 7] 

Входной HostState.txt перечислены различные узлы и их расположение. В экземпляре InstanceState.txt перечислены запущенные экземпляры и на каком хосте они запущены.

+0

Что вы подразумеваете под ссылкой? –

+0

Оба файла содержат HostID. Клиент «8» с HostID «2» имеет три экземпляра, что означает, что он занимает 3 из 4 слотов в HostFile. Я хочу иметь возможность связывать данные и выполнять вычисления на основе клиента, который имеет большинство экземпляров, запущенных на нескольких хостах! –

+0

Ну, конечно, я дам вам направление, но не могу написать код для вас ... Я все еще немного не уверен, как то, что вы пытаетесь сделать, поскольку недостаточно фона, а ваш код/​​организация сообщения немного рассеянный для меня ... Вы пытаетесь указать клиента с хостом/экземпляром из файла экземпляра в определенную позицию в одном из массивов в файле хоста? – Colin

ответ

0

Я предлагаю вам создать два класса для Host и один для экземпляра. Класс Instance будет иметь ссылку на объект Host. Вы также можете использовать встроенную карту для облегчения поиска хостов и экземпляров. Ниже приведены изменения вашего кода, чтобы проиллюстрировать вышеприведенную идею. Я старался сохранить его как можно более согласованным с вашим исходным кодом, хотя я не совсем согласен с вашим дизайном. Во всяком случае, ниже должно дать вам представление о том, как достичь ваши требования:

Host.java

package cloud; 

public class Host { 
    private String hostId; 
    private String numberOfSlots; 
    private String dataCentre; 

    public Host(String hostId, String numberOfSlots, String dataCentre) { 
     this.hostId = hostId; 
     this.numberOfSlots = numberOfSlots; 
     this.dataCentre = dataCentre; 
    } 

    // valid getters and setters follow... 

} 

Instance.java

package cloud; 

public class Instance { 
    private String instanceId; 
    private String customer; 
    private Host host; // this will be a reference to the related host object 

    public Instance(String instanceId, String customer, Host host) { 
     this.instanceId = instanceId; 
     this.customer = customer; 
     this.host = host; 
    } 

    // valid getters and setters follow... 

} 

CloudStructureData.java

package cloud; 

import java.util.HashMap; 
import java.util.Map; 

public class CloudStructureData { 

    private Map<String, Host> hosts; 
    private Map<String, Instance> instances; 

    public CloudStructureData(){ 

     hosts = new HashMap<String, Host>(); // the key will be HostId 
     instances = new HashMap<String, Instance>(); // the key will be InstanceId 
    } 

    public Map<String, Host> getHosts() { 
     return hosts; 
    } 

    public Map<String, Instance> getInstances() { 
     return instances; 
    } 

} 

CloudStructure.java

import java.io.BufferedReader; 
import java.io.FileNotFoundException; 
import java.io.FileReader; 
import java.io.IOException; 
import java.util.Map; 

import cloud.CloudStructureData; 
import cloud.Host; 
import cloud.Instance; 

public class CloudStructure { 

    public static CloudStructureData readHost(String filePath) 
    { 
     String line = ""; 

     CloudStructureData cloudData = new CloudStructureData(); 

     FileReader fr; 
     BufferedReader br; 

     String[] HostID = null; 
     String[] Slots = null; 
     String[] DataCentre = null; 

      try { 
       fr = new FileReader(filePath); 
       br = new BufferedReader(fr); 

       while((line = br.readLine()) != null) 
       { 
        HostID = line.split(","); 
        Slots = line.split(","); 
        DataCentre = line.split(",");     

        Host host = new Host(HostID[0], Slots[1], DataCentre[2]); 

        cloudData.getHosts().put(HostID[0], host); 
       } 
       } 
       catch(FileNotFoundException fN) { 
       fN.printStackTrace(); 
       } 
       catch(IOException e) { 
       System.out.println(e); 
       } 

     // output data the way you want... 

     return cloudData; 
    } 

    public static CloudStructureData readInstance(String filePath, CloudStructureData cloudData) 
    { 
     String line = ""; 

     FileReader fr; 
     BufferedReader br; 

     String[] InstanceId = null; 
     String[] CustId = null; 
     String[] HostId = null; 

      try { 
       fr = new FileReader(filePath); 
       br = new BufferedReader(fr); 

       while((line = br.readLine()) != null) 
       { 
        InstanceId = line.split(","); 
        CustId = line.split(","); 
        HostId = line.split(",");     

        Host hostObject = cloudData.getHosts().get(HostId[2]); // Host object or null if not found 
        Instance instanceObject = new Instance(InstanceId[0], CustId[1], hostObject); 
        cloudData.getInstances().put(InstanceId[0], instanceObject); 
       } 
       } 
       catch(FileNotFoundException fN) { 
       fN.printStackTrace(); 
       } 
       catch(IOException e) { 
       System.out.println(e); 
       } 

       // output instances the way you want 

       return cloudData; 
    } 


    public static void main(String[] args) { 

     CloudStructureData cloudData = readHost("C:\\tmp\\HostState.txt"); 
     cloudData = readInstance("C:\\tmp\\InstanceState.txt", cloudData); 
     /* 
     * All Instances are now linked with Host. 
     * You can loop and do whatever you want. 
     */ 
     for (Map.Entry<String, Instance> currentEntry 
       : cloudData.getInstances().entrySet()) { 
      Instance currentInstance = currentEntry.getValue(); 
      Host currentHost = currentInstance.getHost(); 
      // Now you have the current instance and its related host... 
     } 

    } 
} 

Это то, что вам нужно?

+0

Да, большое спасибо! –