개발자
import java.io.*; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.Scanner; import java.util.regex.Matcher; public class Keyword { public static void main(String[] args) throws IOException { String str,str1; Scanner sc = new Scanner(System.in); System.out.printf("파일에서 찾을 키워드를 입력하세요:"); str = sc.nextLine(); System.out.printf("키워드를 찾을 파일경로를 입력하세요:"); str1 = sc.nextLine(); String testPath = str1; //이 부분 때문에 골치가 아픕니다!!! String OsFilePath = testPath.replaceAll("/", Matcher.quoteReplacement(File.separator)); String path1 = OsFilePath.replaceAll(Matcher.quoteReplacement(File.separator), "/"); Path path2 = Paths.get(path1); String content = Files.readString(path2); String[] result = content.split("\n"); for(int i=0; i<result.length; i++) { if (result[i].contains(str)) { System.out.printf((i+1)+"번째 줄에서\"%s\"이라는 키워드가 감지되었습니다.: \n", str); System.out.println((i+1)+"번째 줄 ->"+result[i]); } } sc.close(); } } 사진대로 나오게 하고 싶습니다.
답변 1
Java에서 입력받은 문자열을 파일 경로로 인식하게 하는 방법은 다음과 같이 처리할 수 있습니다: 아래 코드에서 'File file = new File(str1);' 부분을 추가하여 입력받은 문자열을 파일 경로로 처리합니다. 그 후 'file.exists()'를 사용하여 파일이 실제로 존재하는지 확인합니다. 존재하는 경우 해당 파일의 경로를 사용하여 파일을 읽고 키워드를 찾는 작업을 수행합니다. 파일이 존재하지 않는 경우 "입력된 파일 경로가 유효하지 않습니다."라는 메시지를 출력합니다. 이렇게 하면 Java에서 입력받은 문자열을 파일 경로로 인식하여 처리할 수 있습니다.
1import java.io.*;
2import java.nio.file.Files;
3import java.nio.file.Path;
4import java.nio.file.Paths;
5import java.util.Scanner;
6import java.util.regex.Matcher;
7
8public class Keyword {
9
10 public static void main(String[] args) throws IOException {
11
12 String str, str1;
13 Scanner sc = new Scanner(System.in);
14 System.out.printf("파일에서 찾을 키워드를 입력하세요:");
15 str = sc.nextLine();
16 System.out.printf("키워드를 찾을 파일경로를 입력하세요:");
17 str1 = sc.nextLine();
18
19 File file = new File(str1); // 입력된 파일 경로로 File 객체 생성
20
21 if (file.exists()) { // 파일이 존재하는지 확인
22 String content = Files.readString(file.toPath());
23 String[] result = content.split("\n");
24
25 for (int i = 0; i < result.length; i++) {
26 if (result[i].contains(str)) {
27 System.out.printf((i + 1) + "번째 줄에서\"%s\"이라는 키워드가 감지되었습니다.: \n", str);
28 System.out.println((i + 1) + "번째 줄 ->" + result[i]);
29 }
30 }
31 } else {
32 System.out.println("입력된 파일 경로가 유효하지 않습니다.");
33 }
34
35 sc.close();
36 }
37}
커리어리 AI 봇의 답변을 평가해 주세요!
지금 가입하면 모든 질문의 답변을 볼 수 있어요!
현직자들의 명쾌한 답변을 얻을 수 있어요.
이미 회원이신가요?
지금 가입하면 모든 질문의 답변을 볼 수 있어요!