java를 사용하여 특정 단어가 포함 된 파일의 행을 인쇄하는 방법은 무엇입니까?java를 사용하여 특정 단어가 포함 된 파일의 행을 인쇄하는 방법은 무엇입니까?
파일에서 단어를 찾을 수있는 간단한 유틸리티를 만들고 주어진 단어가있는 전체 줄을 인쇄하고 싶습니다.
나는
java를 사용하여 특정 단어가 포함 된 파일의 행을 인쇄하는 방법은 무엇입니까?java를 사용하여 특정 단어가 포함 된 파일의 행을 인쇄하는 방법은 무엇입니까?
파일에서 단어를 찾을 수있는 간단한 유틸리티를 만들고 주어진 단어가있는 전체 줄을 인쇄하고 싶습니다.
나는
당신이 그런 특정 단어가 포함 된 모든 행을 인쇄하려면 다음 코드를 사용할 수 있습니다은 File2.txt라는 이름의 파일에서 읽고있는 가정하자. 그리고 "foo"라는 단어를 찾고 있다고 가정 해 봅시다.
import java.util.*;
import java.io.*;
public class Classname
{
public static void main(String args[])
{
File file =new File("file1.txt");
Scanner in = null;
try {
in = new Scanner(file);
while(in.hasNext())
{
String line=in.nextLine();
if(line.contains("foo"))
System.out.println(line);
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}}
이 코드가 도움이되기를 바랍니다.
이
같은 것을 수행해야합니다} ... import java.io.*;
public class SearchThe {
public static void main(String args[])
{
try
{
String stringSearch = "System";
BufferedReader bf = new BufferedReader(new FileReader("d:/sh/test.txt"));
int linecount = 0;
String line;
System.out.println("Searching for " + stringSearch + " in file...");
while ((line = bf.readLine()) != null)
{
linecount++;
int indexfound = line.indexOf(stringSearch);
if (indexfound > -1)
{
System.out.println("Word is at position " + indexfound + " on line " + linecount);
}
}
bf.close();
}
catch (IOException e)
{
System.out.println("IO Error Occurred: " + e.toString());
}
}
를 선두로부터 계산이 많은 일을하지만, 그것을 포함하는 행을 인쇄 할 knoe 괭이를하지 않는 한
public void readfile(){
try {
BufferedReader br;
String line;
InputStreamReader inputStreamReader = new InputStreamReader(new FileInputStream("file path"), "UTF-8");
br = new BufferedReader(inputStreamReader);
while ((line = br.readLine()) != null) {
if (line.contains("the thing I'm looking for")) {
//do something
}
//or do this
if(line.matches("some regular expression")){
//do something
}
}
// Done with the file
br.close();
br = null;
}
catch (Exception ex) {
ex.printStackTrace();
}
}
파일을 읽으려면 BufferedReader
또는 Scanner
을보십시오. 문자열에 단어가 들어 있는지 확인하려면 String
-class에서 contains
을 사용하십시오.
몇 가지 노력을 보여 주면 기꺼이 도와 드리겠습니다.
public static void grep(Reader inReader, String searchFor) throws IOException {
BufferedReader reader = null;
try {
reader = new BufferedReader(inReader);
String line;
while ((line = reader.readLine()) != null) {
if (line.contains(searchFor)) {
System.out.println(line);
}
}
} finally {
if (reader != null) {
reader.close();
}
}
}
사용법 :
grep(new FileReader("file.txt"), "GrepMe");
각 줄을 나타내는 String 인스턴스의'contains' 메소드를 사용할 수 있습니다. 가양 성 일치를 피하려면 단어 경계가있는 정규식을 사용할 수 있습니다. 어쨌든 우리가 해결할 수 있도록 코드에 어떤 문제가 있는지 설명해주십시오. – Pshemo
지금까지 해봤습니까? 일부 코드는 제발 ... – Zeeshan
줄 단위로 파일을 읽을 수 있었습니까? 그렇다면 코드가 없습니다. – Smutje