public static void main(String[] args) {
try {
FileInputStream fis = new FileInputStream("D://java.txt");
int b = 0;
while ((b = fis.read()) != -1) {
System.out.print((char) b);
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
输出结果为 C??????????,我们发现中文都是乱码。下面用字节数组,并通过字符串设定编码格式来显式内容,代码如下:
public static void main(String[] args) {
try {
FileInputStream fis = new FileInputStream("D://java.txt");
byte b[] = new byte[1024];
int len = 0;
while ((len = fis.read(b)) != -1) {
System.out.print(new String(b, 0, len, "UTF-8"));
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
这时输出结果为 C语言中文网,但是当存储的文字较多时,会出现解码不正确的问题,且字节长度无法根据解码内容自动设定,此时就需要转换流来完成。代码如下:
public static void main(String[] args) {
try {
FileInputStream fis = new FileInputStream("D://java.txt");
InputStreamReader isr = new InputStreamReader(fis, "UTF-8");
int b = 0;
while ((b = isr.read()) != -1) {
System.out.print((char) b); // 输出结果为“C语言中文网”
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void main(String[] args) {
try {
// 将 System.in 对象转换成 Reader 对象
InputStreamReader reader = new InputStreamReader(System.in);
// 将普通的Reader 包装成 BufferedReader
BufferedReader br = new BufferedReader(reader);
String line = null;
// 利用循环方式来逐行的读取
while ((line = br.readLine()) != null) {
// 如果读取的字符串为“exit”,则程序退出
if (line.equals("exit")) {
System.exit(1);
}
// 打印读取的内容
System.out.println("输入内容为:" + line);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
上面代码第 4 行和第 6 行将 System.in 包装成 BufferedReader,BufferReader 流具有缓冲功能,它可以一次读取一行文本,以换行符为标志,如果它没有读到换行符,则程序堵塞,等到读到换行符为止。运行上面程序可以发现这个特征,在控制台执行输入时,只有按下回车键,程序才会打印出刚刚输入的内容。
版权说明:Copyright © 广州松河信息科技有限公司 2005-2025 版权所有 粤ICP备16019765号
广州松河信息科技有限公司 版权所有