java怎么读取数据
1、从控制台读取数据
使用Scanner类来读取控制台的输入(推荐教程:java教程)
public static void main(String[] args) { Scanner in = new Scanner(System.in); String a = in.nextLine(); System.out.println(a); }
2、从本地读取文件
使用FileInputStream、InputStreamReader、BufferedReader类读取本地数据
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、从网络读取文件
使用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); } }
以上是java怎么读取数据的详细内容。更多信息请关注PHP中文网其他相关文章!