2011-04-08 5 views
12

까지 다음 줄을 얻는 것은 그래서 이것은 내가 지금까지 무엇을 가지고 :텍스트 파일 내부에서 문자열을 찾는 방법. 그런 다음 특정 한도

public String[] findStudentInfo(String studentNumber) { 
       Student student = new Student(); 
       Scanner scanner = new Scanner("Student.txt"); 
       // Find the line that contains student Id 
       // If not found keep on going through the file 
       // If it finds it stop 
       // Call parseStudentInfoFromLine get the number of courses 
       // Create an array (lines) of size of the number of courses plus one 
       // assign the line that the student Id was found to the first index value of the array 
       //assign each next line to the following index of the array up to the amount of classes - 1 
       // return string array 
} 

내가 파일 내가 찾으려고 노력하고있는 문자열을 포함하는 경우 찾는 방법을 알고 있지만 나도 몰라 그 전체 라인을 검색하는 방법

이것은 처음 게시하는 것입니다. 잘못된 것이 있다면 알려주세요.

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

try { 
    Scanner scanner = new Scanner(file); 

    //now read the file line by line... 
    int lineNum = 0; 
    while (scanner.hasNextLine()) { 
     String line = scanner.nextLine(); 
     lineNum++; 
     if(<some condition is met for the line>) { 
      System.out.println("ho hum, i found it on line " +lineNum); 
     } 
    } 
} catch(FileNotFoundException e) { 
    //handle this 
} 
+1

이 숙제 인 경우, 같은 태그되어야한다 : 여기 –

+0

입력 파일의 샘플을 추가 할 수 있습니까? – RonK

답변

31

은 당신이 뭔가를 할 수 있습니까? 이렇게하면 읽는 동안 파일에 줄이 포함되어 있는지 확인할 수 있습니다. 그런 다음 그 논리에 따라 필요한 논리를 수행 할 수 있습니까?

Scanner scanner = new Scanner("Student.txt"); 
String currentLine; 

while((currentLine = scanner.readLine()) != null) 
{ 
    if(currentLine.indexOf("Your String")) 
    { 
     //Perform logic 
    } 
} 

당신은 줄 번호를 유지하기 위해 변수를 사용할 수 있습니다, 또는 당신은 또한 당신이 당신의 문자열이 포함 된 행에 합격 한 경우를 나타내는 boolean 할 수 :

Scanner scanner = new Scanner("Student.txt"); 
String currentLine; 
int lineNumber = 0; 
Boolean passedLine = false; 
while((currentLine = scanner.readLine()) != null) 
{ 
    if(currentLine.indexOf("Your String")) 
    { 
     //Do task 
     passedLine = true; 
    } 
    if(passedLine) 
    { 
     //Do other task after passing the line. 
    } 
    lineNumber++; 
} 
+0

이렇게하면 studentNumber 문자열이 포함 된 행이 표시되지 않습니다. –

+0

좋아, 다시 봐 ... –

+0

오 ~ 알았어. 고맙습니다! –

2

파일을 읽고, 당신은 라인으로 라인을 읽고 생각이 :

+0

해보겠습니다. 너에게 다시 돌아갈 게. –

+0

예를 들어 보겠습니다. –

+0

감사합니다! 나쁜 점을 알려 달라. –

0

나는 비슷한 일을 오전하지만, C++에서. 당신이해야 할 일은 한 번에 하나씩 줄을 읽고 그것들을 파싱합니다 (단어 하나 하나 건너 뜁니다). 나는 모든 라인을 뒤덮는 아웃터 루프 (outter loop)를 가지고 있으며, 그 안에는 모든 단어를 반복하는 또 다른 루프가있다. 필요한 단어를 찾았 으면 루프를 빠져 나와 원하는 카운터 또는 카운터를 반환하십시오.

이것은 내 코드입니다. 기본적으로 모든 단어를 분석하여 "색인"에 추가합니다. 단어가 들어있는 행은 벡터에 추가되고 색인 된 단어에서 행 (파일 이름, 전체 행 및 줄 번호 포함)을 참조하는 데 사용됩니다. 나는이 기능 FileUtils.readFileToString(file).contains(stringToFind)

문서를 사용하여이를 확립 할 수 있었다 아파치 커먼즈 IO의 API https://commons.apache.org/proper/commons-io/를 사용

ifstream txtFile; 
txtFile.open(path, ifstream::in); 
char line[200]; 
//if path is valid AND is not already in the list then add it 
if(txtFile.is_open() && (find(textFilePaths.begin(), textFilePaths.end(), path) == textFilePaths.end())) //the path is valid 
{ 
    //Add the path to the list of file paths 
    textFilePaths.push_back(path); 
    int lineNumber = 1; 
    while(!txtFile.eof()) 
    { 
     txtFile.getline(line, 200); 
     Line * ln = new Line(line, path, lineNumber); 
     lineNumber++; 
     myList.push_back(ln); 
     vector<string> words = lineParser(ln); 
     for(unsigned int i = 0; i < words.size(); i++) 
     { 
      index->addWord(words[i], ln); 
     } 
    } 
    result = true; 
} 
+0

도움이되는 동안, OP는 Java 기반 솔루션을 요구하고 있었다. C++ 파일 작업은 Java의 파일 작업과 상당히 다르므로이 대답은이 컨텍스트에서 전체적으로 도움이되지 않습니다. –

-1

에서 TextScanner

의 코드
public class TextScanner { 

     private static void readFile(String fileName) { 
      try { 
       File file = new File("/opt/pol/data22/ds_data118/0001/0025090290/2014/12/12/0029057983.ds"); 
       Scanner scanner = new Scanner(file); 
       while (scanner.hasNext()) { 
       System.out.println(scanner.next()); 
       } 
       scanner.close(); 
      } catch (FileNotFoundException e) { 
       e.printStackTrace(); 
      } 
      } 

      public static void main(String[] args) { 
      if (args.length != 1) { 
       System.err.println("usage: java TextScanner1" 
       + "file location"); 
       System.exit(0); 
      } 
      readFile(args[0]); 
     } 
} 
입니다

delimeter로 텍스트를 인쇄합니다

for (String toFindUrl : urlsToTest) { 
     streamService(toFindUrl); 
    } 

private void streamService(String item) { 
     String tmp; 
     try (Stream<String> stream = Files.lines(Paths.get(fileName))) { 
      tmp = stream.filter(lines -> lines.contains(item)) 
         .foreach(System.out::println); 

     } catch (IOException e) { 
      e.printStackTrace(); 
     } 
    } 
1
텍스트 파일에 문자열을 찾을 수있는 자바 (8) 방법이다.
관련 문제