How to read data in java
1. Read data from the console
Use the Scanner class to read input from the console(Recommended tutorial:java tutorial)
public static void main(String[] args) { Scanner in = new Scanner(System.in); String a = in.nextLine(); System.out.println(a); }
2. Read files from local
Use FileInputStream, InputStreamReader, and BufferedReader classes to read local data
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("文件读取错误!"); } }
3. Read files from the network
Use URLConnection, InputStreamReader, and BufferedReader to read network data.
public class Main { public static void main(String[] args) { String url = "//m.sbmmt.com/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); } }
The above is the detailed content of How to read data in java. For more information, please follow other related articles on the PHP Chinese website!