개발자
스캐너로 경로를 입력해서 정보를 나오게 하고 싶은데 어떻게 해야 할까요?
답변 2
익명
작성자
2023년 05월 16일
public static void main(String[] args) throws IOException { String str; Scanner sc = new Scanner(System.in); str = sc.nextLine(); String nstr= str.replace("\\","/"); System.out.println(nstr); Path path = Paths.get(nstr); try { String content = Files.readString(path); System.out.println(content); }catch (IOException e){ e.printStackTrace(); } sc.close(); }
Java의 Scanner 클래스를 이용하여 사용자로부터 파일 경로를 입력받아, 그 파일의 내용을 읽는 프로그램을 작성하려면 다음과 같이 할 수 있습니다. 아래 코드는 사용자로부터 파일 경로를 입력받고, 해당 경로의 파일 내용을 출력하는 프로그램입니다. Files.readAllBytes와 Paths.get을 사용하여 파일의 모든 내용을 읽어들입니다. 주의할 점은, 입력받은 경로에 파일이 실제로 존재하고, 읽을 수 있는 권한이 있는지 확인해야 합니다. 그렇지 않으면 IOException이 발생하게 됩니다. 이 예외는 try-catch 문으로 처리하였습니다.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
import java.util.Scanner; import java.nio.file.Files; import java.nio.file.Paths; import java.io.IOException; public class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.println("파일 경로를 입력하세요: "); String filePath = scanner.nextLine(); try { String fileContent = new String(Files.readAllBytes(Paths.get(filePath))); System.out.println("파일 내용: \n" + fileContent); } catch (IOException e) { System.out.println("파일 읽기에 실패하였습니다. 경로를 확인해주세요."); } scanner.close(); } }
커리어리 AI 봇의 답변을 평가해 주세요!
지금 가입하면 모든 질문의 답변을 볼 수 있어요!
현직자들의 명쾌한 답변을 얻을 수 있어요.
이미 회원이신가요?
지금 가입하면 모든 질문의 답변을 볼 수 있어요!