Chia sẻ kiến thức
Bạn có muốn phản ứng với tin nhắn này? Vui lòng đăng ký diễn đàn trong một vài cú nhấp chuột hoặc đăng nhập để tiếp tục.

Chương 1: Thao tác Nhập/Xuất trong Java

Go down

Chương 1: Thao tác Nhập/Xuất trong Java Empty Chương 1: Thao tác Nhập/Xuất trong Java

Bài gửi  Admin Mon Sep 02, 2013 3:10 pm

Ví dụ 4: Nhập dữ liệu dạng ký tự (dùng Reader) từ bàn phím: (dạng trung gian) Luồng ký tự > Trung gian > Luồng bytes
-Nếu là số in ra màn hình "I read this number: " + số vừa nhập.
-Nếu không phải là số, bắt lỗi và in ra màn hình "Not a valid number: " + kí tự vừa nhập.
-Nếu là lỗi không mong đợi, bắt ngoại lệ và in ra màn hình: "Unexpected IO ERROR: " + lỗi đó.

Code:

import java.io.*;
class ReadStdinInt{
 public static void main(String[] args){
 String line = null;
 int val = 0;
 try{
 InputStreamReader isr = new InputStreamReader(System.in);
 BufferedReader br = new BufferedReader(isr);
 line = br.readLine();
 val = Integer.parseInt(line);
 } catch (NumberFormatException ex){
 System.err.println("Not a valid number: "+line);
 } catch (IOException ie){
 System.err.println("Unexpected IO ERROR: "+ie);
 }
 System.out.println("I read this number: "+val);
 }
}
---
STREAM XUẤT:
Ví dụ 1: Cho chuỗi String: "The example of OutputStream" , in ra màn hình dùng Stream xuất
Code:

import java.io.*;
public class OutStream1{
 public static void main(String args[]){
 OutputStream os = System.out; //Monitor
 try{
 String str = "The example of OutputStream\n";
 byte b[] = str.getBytes();
 os.write(b);
 }
 catch(IOException ie){
 System.out.println("Error: " + ie);
 }
 }
}
Ví dụ 2: cho biến int val = 12345, chuyển: int > string > byte[] rồi xuất ra file "test.txt", dùng FileOutputStream.
---
COPY-PASTE:
Code:

import java.io.*;
import java.util.*;
class copypaste {
 public static void main(String[] args) {
 try{
 System.out.print("Nhap ten tap tin can copy: ");
 Scanner sc1  = new Scanner(System.in);
 String fis = sc1.nextLine();
 System.out.print("Nhap ten tap tin can paste: ");
 Scanner sc2  = new Scanner(System.in);
 String fos = sc2.nextLine();
 InputStream is = new FileInputStream("c:/"+fis+".txt");
 OutputStream os = new FileOutputStream("c:/"+fos+".txt");
 while(true){
 int ch=is.read();
 if(ch == -1) break;
 os.write(ch);
 }//while
 }//try
 catch(IOException e){
 e.printStackTrace();
 }
 }
}
Admin
Admin
Admin

Tổng số bài gửi : 218
Reputation : 22
Join date : 17/11/2012
Age : 32

https://elcit.forumvi.com

Về Đầu Trang Go down

Về Đầu Trang

- Similar topics

 
Permissions in this forum:
Bạn không có quyền trả lời bài viết