通过available()方法实现不阻塞输入流
FileInputStream fis = new FileInputStream(f);
try {
//通过available()方法可以实现不阻塞流
byte[] b = new byte[fis.available()];
int result = 0;
while((result = fis.read(b)) != -1) {
System.out.println(new String(b, "utf-8"));
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
fis.close();
读取文件
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
public class FileInputStreamJava {
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
String strFile = "d:" + File.separator + "javatest" + File.separator + "IO_RandomAccessFileTest.txt";
File f = new File(strFile);
FileInputStream fis = new FileInputStream(f);
byte[] b = new byte[1024];
int result = 0;
while((result = fis.read(b)) != -1) {
//数组b固定大小1024,所以如果读到的数据不足,数组会自动填满,输出的时候结尾就可能会出现乱码
//下面这种方式就出现了乱码
//System.out.println(new String(b, "utf-8"));
//现在这样就不会出现乱码了,重新组装成字符串的时候确定了最后一个字符串的byte数组大小
System.out.println(new String(b,0,result, "utf-8"));
}
fis.close();
}
}
每次读一个字节
public class FileInputStreamJava {
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
String strFile = "d:" + File.separator + "javatest" + File.separator + "IO_RandomAccessFileTest.txt";
File f = new File(strFile);
FileInputStream fis = new FileInputStream(f);
//byte[] b = new byte[1024];
int result = 0;
while((result = fis.read()) != -1) {
//数组b固定大小1024,所以如果读到的数据不足,数组会自动填满,输出的时候结尾就可能会出现乱码
//下面这种方式就出现了乱码
//System.out.println(new String(b, "utf-8"));
//现在这样就不会出现乱码了,重新组装成字符串的时候确定了最后一个字符串的byte数组大小
System.out.print((char)result);
}
fis.close();
}
}
写数据
import java.io.File;
import java.io.FileOutputStream;
public class FileOutputStreamJava {
public static void main(String[] args) throws Exception {
// TODO Auto-generated method stub
String strFile = "d:" + File.separator + "javatest" + File.separator + "IO_RandomAccessFileTest.txt";
File f = new File(strFile);
//true,将字节写入文件末尾处,而不是写入文件开始处
FileOutputStream fos = new FileOutputStream(f, true);
// \r\n是windows系统的换行符
byte[] b = "\r\n写出数据...".getBytes();
fos.write(b);
fos.close();
}
}