텍스트 파일에서 데이터를 읽고 내가 처음 공간 라인과 분리하여이 줄을 읽고 세트에 저장하려는구문 분석은 내가 다음과 같은 형식으로 내 텍스트 파일에 데이터가
apple fruit
carrot vegetable
potato vegetable
또는 지도 또는 자바의 유사한 컬렉션. (키 및 값 쌍)
예 -
"apple fruit"
가지도 key = apple
및 value = fruit
에 저장되어야한다.
텍스트 파일에서 데이터를 읽고 내가 처음 공간 라인과 분리하여이 줄을 읽고 세트에 저장하려는구문 분석은 내가 다음과 같은 형식으로 내 텍스트 파일에 데이터가
apple fruit
carrot vegetable
potato vegetable
또는 지도 또는 자바의 유사한 컬렉션. (키 및 값 쌍)
예 -
"apple fruit"
가지도 key = apple
및 value = fruit
에 저장되어야한다.
Scanner 클래스는 아마도 당신이 쫓고있는 것입니다.
Scanner sc = new Scanner(new File("your_input.txt"));
while (sc.hasNextLine()) {
String line = sc.nextLine();
// do whatever you need with current line
}
sc.close();
당신은 같은 것을 할 수 있습니다 : 예를 들어
BufferedReader br = new BufferedReader(new FileReader("file.txt"));
String currentLine;
while ((currentLine = br.readLine()) != null) {
String[] strArgs = currentLine.split(" ");
//Use HashMap to enter key Value pair.
//You may to use fruit vegetable as key rather than other way around
}
당신이지도를 원하는 경우 자바 8 단지
Set<String[]> collect = Files.lines(Paths.get("/Users/me/file.txt"))
.map(line -> line.split(" ", 2))
.collect(Collectors.toSet());
을 할 수 있기 때문에, Collectors.toMap()에 의해 Collectors.toSet을 대체 할 수 있습니다.
Map<String, String> result = Files.lines(Paths.get("/Users/me/file.txt"))
.map(line -> line.split(" ", 2))
.map(Arrays::asList)
.collect(Collectors.toMap(list -> list.get(0), list -> list.get(1)));
안녕하세요. 이 주제에 대한 연구에 많은 시간을 투자하지 않은 것 같습니다. 그렇지 않으면 수많은 예제를 발견했을 것입니다. 여전히 커뮤니티의 도움이 필요하다고 생각하시는 경우, 논의 할 수있는 솔루션에 대한 코드를 제시하고 개선을 제안하십시오. 누군가가 당신을 위해 완전한 일을 기꺼이 수행 할 것 같지 않습니다. –