2016-04-04 22 views
2

Bir aracın ayrıntılarını x koordinatı ve y koordinatıyla bir metin belgesinden kaydetmeye çalışıyorum. Burada metin belgesi neye benziyor ('760' kasten başka bir satırdadır)Metin dosyasından okuma, ancak yalnızca belirli parçaları depola

Dosyayı okumak için bir yol olup olmadığını ve sadece araç adını ve x & y koordinatlarını saklamak için bir yol olup olmadığını merak ediyorum. Zaten bir ad almak için bir kurucu var, x & y. Ben de kurmak bu Tarayıcı vardır: Ben .next(); kullanarak insanların etrafına baktı ve gördüğüm

File file; 
      file = new File("CarInfo.txt"); 

      try (Scanner sc = new Scanner(file)) { 
    while (sc.hasNext()) { 
     String carTab = sc.next(); 
     // Looking for tag 'Car' 
     if (!carTab.equals("Car:")) continue; 

     if (!sc.hasNext()) { 
      break; 
     } 

     String car = sc.next(); 
     if (!sc.hasNextInt()) { 
      continue; 
     } 
     int x = sc.nextInt(); 
     if (!sc.hasNextInt()) { 
      break; 
     } 
     int y = sc.nextInt(); 
     System.out.println(car + " " + x + " " + y); 
    } 



} catch (FileNotFoundException e) { 
    System.out.println("File not found"); 
} 

ama işe alınamıyor.

Düzenleme: (Keqiang Li) koddan Alınan

Hata:

Exception in thread "AWT-EventQueue-0" java.util.InputMismatchException 
    at java.util.Scanner.throwFor(Scanner.java:864) 
    at java.util.Scanner.next(Scanner.java:1485) 
    at java.util.Scanner.nextDouble(Scanner.java:2413) 
    at traingui.code.TrainGui$1.run(TrainGui.java:37) 
    at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:311) 
    at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:756) 
    at java.awt.EventQueue.access$500(EventQueue.java:97) 
    at java.awt.EventQueue$3.run(EventQueue.java:709) 
    at java.awt.EventQueue$3.run(EventQueue.java:703) 
    at java.security.AccessController.doPrivileged(Native Method) 
    at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:76) 
    at java.awt.EventQueue.dispatchEvent(EventQueue.java:726) 
    at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:201) 
    at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:116) 
    at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:105) 
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:101) 
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:93) 
    at java.awt.EventDispatchThread.run(EventDispatchThread.java:82) 
+0

_ "120", başka bir satırda "_" bir "hata" olduğu için düzeltildi ve düzeltilebilir mi? Dosya hakkında başka anormallikler var mı? _could_ yapmak, dosyayı bir akış olarak ele alır, burada yeni satırlar önemsizdir (diğer herhangi bir boşluk gibi davranır) ve bir dizi 4 "alan" ayrıştırır - sabit "İstasyon:", beyaz boşluk, _StationName_ boşluk, _x_, boşluk, _y_ –

cevap

1
public static void main(String[] args) throws FileNotFoundException { 
    File file = new File("StationInfo.txt"); 

    try (Scanner sc = new Scanner(file)) { 
     while (sc.hasNext()) { 
      String stationTab = sc.next(); 
      // Looking for tag 'Station:' 
      if (!stationTab.equals("Station:")) continue; 

      if (!sc.hasNext()) { 
       break; 
      } 

      String station = sc.next(); 
      if (!sc.hasNextInt()) { 
       continue; 
      } 
      int x = sc.nextInt(); 
      if (!sc.hasNextInt()) { 
       continue; 
      } 
      int y = sc.nextInt(); 
      System.out.println(station + " " + x + " " + y); 
     } 

    } catch (FileNotFoundException e) { 
     System.out.println("File not found"); 
    } 
} 
+0

Bu hatayı bu koddan aldım ama neye sebep olduğunu göremiyorum? (Yukarıdaki kodda hata içeriyordu) – BlaBla

+0

@Safa Bu, dosyanızın hatalı biçimlendirilebileceğinden dolayı, cevabımda bahsettiğim bir hatadır. Bu nedenle, bir çiftin bekleneceği, ancak dosyada başka bir şey ortaya çıkması durumunda ele almanız gerekir.Bu elbette bir uyumsuzluk istisnası atacaktır. Dosyanızda daha fazla hatalı biçimlendirilmiş olasılıklar, bunları işlemek için buraya eklemeniz gereken daha fazla kod. –

+0

Bunu daha sonra catch bölümüne ekleyeceğim mi? – BlaBla

0

Bu değerler iki hat arasında bölünebilir dikkate alarak, iş yapacak.

import java.io.*; 
import java.util.Scanner; 

public class StationTest { 
    public static void main(String[] args) { 
     File file = new File("StationInfo.txt"); 
     String token1 = ""; 
     try { 
      Scanner sc = new Scanner(file); 
      while (sc.hasNext()) { 
       String[] acceptedValues = new String[3]; 
       String line = sc.nextLine(); 
       String[] values = line.split(" "); 

       for (int i = 1; i < values.length; i++) { 
        acceptedValues[i - 1] = values[i]; 
       } 

       if (values.length < 4) { 
        String nextLine = sc.nextLine(); 
        String[] nextLineValues = nextLine.split(" "); 
        for (int i = 1; i <= acceptedValues.length + 1 - values.length; i++) { 
         acceptedValues[values.length + i - 2] = nextLineValues[i - 1]; 
        } 
       } 
      } 

      // Do as you wish with these values, setting them in your model class. 
      System.out.println("Name: " + acceptedValues[0]); 
      System.out.println("X: " + acceptedValues[1]); 
      System.out.println("Y: " + acceptedValues[2]); 

      sc.close(); 
     } catch (FileNotFoundException e) { 
      e.printStackTrace(); 
     } 
    } 
} 
0

Bir regex ile sorunu çözebilir:

File file = new File("StationInfo.txt"); 

    String line = ""; 

    try { 

     Scanner sc = new Scanner(file); 

     while (sc.hasNextLine()) { 

      String name; 
      double x; 
      double y; 

      // find next line 
      String temp = sc.nextLine(); 
      try { 
       Double.parseDouble(temp); 
       line += " " + temp; 
      } catch(NumberFormatException e) { 
       line = temp; 
      } 

      String regex = "^(\\w+:)\\s(\\w+)\\s(\\d+)\\s+(\\d+)"; 

      if(line.matches(regex)) { 
       name = line.replaceAll(regex, "$2"); 
       x = Double.parseDouble(line.replaceAll(regex, "$3")); 
       y = Double.parseDouble(line.replaceAll(regex, "$4")); 
       System.out.println("Name = " + name + ", x = " + x + ", y = " + y); 
      } 

      // TrainNetwork.newStation.addStation(token1); 
     } 
     sc.close(); 



     // System.out.println(TrainNetwork.newStation); 


    } catch (FileNotFoundException e) { 
     e.printStackTrace();  
    } 

İşte regex farklı dize parçalar ve depolar adı, x ve y adında 3 değişkenlerde veri bulabilirsiniz.

DÜZENLEME: Artık kod, satır başı dönüşü olup olmadığını algılar ve ayrıca son veri satırıyla çalışır. kelimeler bu String regex = "^(\\w+:)\\s+(\\w+)\\s+(\\d+)\\s+(\\d+)";

ile regex değiştirmek emin olun arasındaki birden fazla boşluk eklemek istiyorsanız Ve Erken "Station:" değişti içine "Yer:" böylece size umursamıyor farz ilk sözcük ancak eğer "İstasyon:" ile başlıyorsa dizgeyi kabul etmek istiyorsanız, sadece String regex = "^(Station:)\\s(\\w+)\\s(\\d+)\\s+(\\d+)";

+0

'TrainNetwork.newStation.addStation()' adlı bir şeyi yorumladım çünkü kodum yok ve nasıl kullanacağımı bilmiyorum. – aleb2000

0

ile normal ifadeyi değiştirin. İstasyonlar için başka bir Nesne oluşturabilir ve her İstasyon nesnesini bir ArrayList dosyasında aynı dosyada saklayabilirsiniz Dosya Okuma kodunuz var:

İstasyon Nesnesi

public class Station { 

    private String name; 
    private ArrayList<Double> coords; 

    public Station(String name, ArrayList<Double> coords){ 
     this.name = name; 
     this.coords = coords; 
    } 

} 

Kişisel Kod

File file = new File("StationInfo.txt"); 
    Scanner sc = new Scanner(file); 
    ArrayList<Station> stationObj = new ArrayList<>(); 
    ArrayList<Double> temp = new ArrayList<>(); 
    String stationName = ""; 

    while (sc.hasNext()) { 
     String token = sc.next(); 

     if (!token.trim().equalsIgnoreCase("Station:")) {  
      try{ 
       temp.add(Double.parseDouble(token)); 
      } catch (Exception e){ 
       stationName = token; 
      } 
     } 

     // The below will work for when you have 1 coordinate or both coordinates. 

     if(!stationName.equals("") && !stationName.equalsIgnoreCase("Station:") && !temp.isEmpty() && (!sc.hasNextDouble() || !sc.hasNextInt())){ 
      stationObj.add(new Station(stationName, temp)); 
      temp = new ArrayList<>(); 
      stationName = ""; 
     } 

    } 

, debug ve stationObj Arraylist bakarsak Modifiye, listenin içindeki her İstasyon nesnesinde saklanan her istasyonu ve gibi koordinatlarını göreceksiniz.

İlgili konular