>  기사  >  Java  >  자바에서 데이터를 읽는 방법

자바에서 데이터를 읽는 방법

angryTom
angryTom원래의
2019-11-12 13:18:494263검색

자바에서 데이터를 읽는 방법

Java에서 데이터를 읽는 방법

1. 콘솔에서 데이터 읽기

Scanner 클래스를 사용하여 콘솔에서 입력을 읽습니다(추천 튜토리얼: java 튜토리얼 E) r

public static void main(String[] args) {
    Scanner in = new Scanner(System.in);
  String a = in.nextLine();
  System.out.println(a);
}

2, 로컬에서 파일 읽기

FileInpputStream, InputStreamReader, BufferEdream 클래스를 사용하여 로컬 데이터 읽기

 public void readTxtFile(String filePath) {
        try {
            File file = new File(filePath);
            if (file.isFile() && file.exists()) {
                InputStreamReader isr = new InputStreamReader(new FileInputStream(file), "utf-8");
                BufferedReader br = new BufferedReader(isr);
                String lineTxt = null;
                while ((lineTxt = br.readLine()) != null) {
                    System.out.println(lineTxt);
                }
                br.close();
            } else {
                System.out.println("文件不存在!");
            }
        } catch (Exception e) {
            System.out.println("文件读取错误!");
        }
    }
E


3, 인터넷에서 파일 읽기

UrLConnection, InputStreamReader,,, , , BufferedReader는 네트워크 데이터를 읽습니다.

public class Main {
    public static void main(String[] args) {
    String url = "http://www.php.cn/test.txt";
    String result = "";
    BufferedReader in = null;
    try {
        //生成URL
        URL realUrl = new URL(url);
        //初始化连接到特定URL的连接通道
        URLConnection connection = realUrl.openConnection();
        //开始实际连接
        connection.connect();
        //数据读取
        in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        
        //临时存储一行数据
        String line;
        while((line = in.readLine()) != null) {
            result += line;
        }
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        try {
            if (in != null) {
                in.close();
            }
        } catch (Exception e2) {
            e2.printStackTrace();
        }
    }
    System.out.println(result);
  }
}

위 내용은 자바에서 데이터를 읽는 방법의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.