2013-10-07 2 views
1

파일에서 문장으로 문장을 저장 한 다음 번호로 구성된 다음 줄을 문자열에 저장할 수 있습니까?파일의 문장을 문자열에 저장 java

hasNextline 또는 nextLine을 사용할 때 아무 것도 작동하지 않습니다. 나 진짜 혼란 스럽다.

 Scanner kb = new Scanner(System.in); 
    String secretMessage = null; 
    String message, number = null; 
    File file = new File(System.in); 
    Scanner inputFile = new Scanner(file); 

    while(inputFile.hasNext()) 
    { 
      message = inputFile.nextLine(); 
      number = inputFile.nextLine(); 
    } 


    System.out.println(number + "and " + message); 
+2

더 나은 도움을 얻기 위해 시도한 것을 [SSCCE] (http://sscce.org/)에 게시하십시오. – Josh

답변

0

당신은 전체 파일에 걸쳐 반복하여 messagenumber 변수를 덮어 쓰기 한 다음 바로 끝에서 한 번에 인쇄하고 있습니다. 루프 내에서 print 문을 움직여서 모든 행을 인쇄합니다.

 while(inputFile.hasNext()) 
     { 
      message = inputFile.nextLine(); 
      number = inputFile.nextLine(); 
      System.out.println(number + "and " + message); 
     } 
+0

좋아,하지만 어떻게해야합니까 filereader, 나를 위해 일하지 않는 내가 명령 프롬프트 메시지

+0

에서 이것을 할 필요가있다. 입력 리다이렉션 ('<')을 사용하는 것은 내가 일반적으로 읽는 방법이 아니다. 자바 파일에서. 일반적으로 파일 이름을 인수로 취하고 파일을 열고 파일을 닫은 다음 파일을 닫습니다. 프로그램을 "java MyProgram filename.txt"로 실행 한 다음 프로그램의 내부에서 "filename.txt"에 액세스하여 args [0]을 입력하십시오. 다음은 그 예입니다 : http://stackoverflow.com/questions/4716503/best-way-to-read-a-text-file. – alexroussos

+0

어떤 이유에서 건 '<'를 사용하여 파일을 읽는 것이 어려울 경우이 질문에서 스캐너가 올바르게 작동하고 BufferedReader가 아닌 코드를 사용해 볼 수 있습니다. http://stackoverflow.com/questions/5918525/piping-input-using-java-using-command-line – alexroussos

0

한 줄에서 파일을 읽으려면 Files.readAllLines() 메서드를 사용하는 것이 좋습니다.

import java.io.BufferedWriter; 
import java.io.IOException; 
import java.nio.file.Files; 
import java.nio.file.Paths; 
import java.util.List; 

public class Display_Summary_Text { 

public static void main(String[] args) 
{ 
    String fileName = "//file_path/TestFile.txt"; 

    try 
    { 
     List<String> lines = Files.readAllLines(Paths.get(fileName), Charset.defaultCharset()); 
     String eol = System.getProperty("line.separator"); 
     for (int i = 0; i <lines.size(); i+=2) 
     { 
      System.out.println(lines.get(i).toString() + "and" + lines.get(i+1) + eol); 
     } 
    }catch(IOException io) 
    { 
     io.printStackTrace(); 
    } 
} 
} 

이 설정을 사용하면 필요에 따라 파일에 출력을 저장하기 위해 stringBuilder 및 Writer를 만들 수도 있습니다.

관련 문제