2012-12-04 3 views
-1

나는 파싱해야 할 파일이있다. 문제는 간단하지만 나는 어떤 진로도 얻지 못하고있다. 문제는 다음과 같습니다. 파일에는 20-22 줄의 청크에 데이터가 들어 있으며 그 다음에는 알려지지 않은 빈 줄 수와 다시 20-22 줄의 청크가옵니다. 나는이 데이터 척의 데이터 구조를 만들 필요가있다. 나는 다음과 같은파일 파싱에 관하여

File f1 = new File(PATH_TO_TRAINING_FILE); 
FileInputStream fis1 = new FileInputStream(f1); 
readerTrainingFile = new BufferedReader(new InputStreamReader(fis1)); 
String trainLine; 
while ((trainLine =readerTrainingFile.readLine()) != null) { 
    ArrayList<String> train = new ArrayList<String>(); 
    while (!trainLine.trim().equals("")) { 
     train.add(trainLine); 
     trainLine =readerTrainingFile.readLine(); 
    } 
    while (readerTrainingFile.readLine().trim().equals("")) { 
    } 
} 

그래서 위의 코드에 문제가 시도하는 동안 세 번째 난 후, 빈 라인이 아닌 첫 번째 공간으로 읽기 라인 이동의 포인터를 점검을 완료 한 루프 동안 다음 덩어리의 라인. 그래서, 내 컨트롤이 첫 번째 while 루프에 도달하면, 내가 원하는 두 줄의 데이터를 건너 뜁니다. 질문이 정말 쉽다면 정말 미안합니다. 나는 지금 2 일 동안 그것에 붙어있다. 어떤 도움을 주셔서 감사합니다.

답변

2

줄 바꾸기 readerTrainingFile.readLine()은 프로그램에서 한 번만 나타납니다. 중첩 된 루프는 자신을 위해 비참한 삶을 살 수있는 좋은 방법입니다. 줄을 건너 뛰려면 continue 문을 사용하십시오. 디버깅을 위해 System.out.println(trainLine)을 사용하면 읽고있는 내용을 볼 수 있으며 매번 건너 뛸 수도 있습니다. 이러한 단계를 통해 문제를 해결할 수 있습니다.

+0

감사합니다, 나는 시도 할 것이다 이것을하기 위해. – shaun

0
while ((trainLine =readerTrainingFile.readLine()) != null) { 
      ArrayList<String> train = new ArrayList<String>(); 
      while (!trainLine.trim().equals("")) { 
       train.add(trainLine); 
       trainLine =readerTrainingFile.readLine(); 
      } 
      while (readerTrainingFile.readLine().trim().equals("")) { 

      } 
} 

문제가 있습니다. 라인을 두 번 읽었습니다. 그냥 처음 while 루프에서이 코드를 넣어 :

if (trainLine.trim().equals("")) { 
    train.add(trainLine); 
} 

또한, 또 다른 문제는이 이동 :

ArrayList<String> train = new ArrayList<String>(); 

를 루프 중. 그렇지 않으면 라인을 읽을 때마다 새로운 것이 만들어집니다.

1

List<List<String>> trains = new ArrayList<List<String>>(); 
List<String> curTrain = null; 
while ((trainLine=readerTrainingFile.readLine()) != null) { 
    if (!trainLine.trim().equals("")) 
     curTrain = null; 
    else 
    { 
     if (curTrain == null) 
     { 
      curTrain = new ArrayList<String>(); 
      trains.add(curTrain); 
     } 
     curTrain.add(trainLine) 
    } 
} 

trains 같은 모든 청크를 포함하는 목록입니다 고려. 데이터를 읽는 동안 curTrain은 현재 행이 추가되는 청크를 나타냅니다. 공백이 아닌 줄을 가져올 때마다 현재 청크에 추가하지만 현재 청크가없는 경우 (시작 부분에 있거나 하나 이상의 이전 줄이 비어 있으므로 새 줄을 만들고 청크 목록에 추가하십시오.

0
Scanner scanner = new Scanner(f1); 
ArrayList<String> train = new ArrayList<String>(); 
while(scanner.hasNextLine()){ 
    String temp = scanner.nextLine(); 
    if(!temp.trim().equals("")) 
     train.add(temp); 
} 

당신은

(temp = reader.nextLine()) != null 

해당 버퍼 리더 scanner.hasNextLine을 대체 할 수 그러나 스캐너 이해 + 사용하는 것이 조금 더 쉽다. 첫 번째 while 루프 내에서 문자열을 추가하므로 arraylist는 로컬이며 루프가 완료된 후에도 지속되지 않습니다 (reader.nextLine() == null).

동일한 유형에! = 및! .equals()를 사용하고 있습니다. 이것은 문자열에 대해서는 문제가 없지만 일반적으로 .equals는 객체에 사용되며 ==는 프리미티브에 사용됩니다 (java는 객체와 프리미티브 사이의 문자열을 처리합니다).

0

"청크"가 무엇을 나타내는 지 모르지만 목록 문자열보다 더 나은 추상화를 상상해보십시오.

package cruft; 

import org.apache.commons.io.IOUtils; 
import org.apache.commons.lang3.StringUtils; 

import java.io.*; 
import java.util.LinkedList; 
import java.util.List; 
import java.util.Map; 
import java.util.TreeMap; 

/** 
* FileChunkParser description here 
* @author Michael 
* @link 
* @since 12/4/12 6:06 PM 
*/ 
public class FileChunkParser { 

    public static void main(String[] args) { 
     try { 
      File f = new File((args.length > 0) ? args[0] : "resources/chunk.txt"); 
      Reader reader = new FileReader(f); 
      FileChunkParser parser = new FileChunkParser(); 
      Map<Integer, List<String>> chunks = parser.parse(reader); 
      for (int index : chunks.keySet()) { 
       System.out.println(String.format("index: %d chunk: %s", index, chunks.get(index))); 
      } 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } 
    } 

    public Map<Integer, List<String>> parse(Reader reader) throws IOException { 
     Map<Integer, List<String>> chunks = new TreeMap<Integer, List<String>>(); 
     BufferedReader br = null; 
     try { 
      if (reader != null) { 
       br = new BufferedReader(reader); 
       int chunkCount = 0; 
       String line = ""; 
       List<String> chunk = null; 
       while ((line = br.readLine()) != null) { 
        if (StringUtils.isBlank(line)) { 
         if (chunk != null) { 
          chunks.put(chunkCount++, new LinkedList<String>(chunk)); 
          chunk = null; 
         } 
         continue; 
        } else { 
         if (chunk == null) { 
          chunk = new LinkedList<String>(); 
         } 
         chunk.add(line); 
        } 
       } 
       if (chunk != null) { 
        chunks.put(chunkCount++, chunk); 
       } 
      } 
     } finally { 
      IOUtils.closeQuietly(reader); 
     } 
     return chunks; 
    } 
} 

내가이 입력 파일을 실행 : 여기

this 
is 
how 
you 
do 
it 



see 
how 
it 
handles 
arbitrary 
sized 
chunks 
with 
any 
blank 
lines 
between 

try 
it 
and 
see 

그리고 출력있어 :

여기 당신이 그것을 해결할 수있는 하나의 방법입니다

index: 0 chunk: [this, is, how, you, do, it] 
index: 1 chunk: [see, how, it, handles, arbitrary, sized, chunks, with, any, blank, lines, between] 
index: 2 chunk: [try, it, and, see]