读取一个文件中的信息
public class IOinput {
private static final String FilePath="src/exercise/exercise.java";//文件所在位置
public static void main(String[] args) throws IOException {
File file=new File(FilePath);
InputStream inputstream=new FileInputStream(file);
byte[]bytes=new byte[999999];//999999是因为available函数只能估计文件大小,可能会达不到预期,所以这里用999999
int count=0;
while((bytes[count]=(byte)inputstream.read())!=-1) {
count++;
}
String content=new String(bytes);
long EndTime=System.currentTimeMillis();
System.out.println(content);
}
}
在一个文件中写入信息
public class IOoutpit {
public static void main(String[] args) throws IOException {
final String FiePath1="src/exercise/IOoutput1.java";//这里默认的是没有的文件
OutputStream outputstream=new FileOutputStream(FiePath1);
String str="123123";
outputstream.write(str.getBytes());
outputstream.close();
}
}
读取一个文件的信息
public class IObinput {
static final String Filepath="src/exercise/exercise.java";
public static void main(String[] args) throws IOException {
File file=new File(Filepath);
InputStream inputstream=new FileInputStream(file);
BufferedInputStream bInputstream=new BufferedInputStream(inputstream);
byte[]bytes=new byte[999999];
int count=0;
while((bytes[count]=(byte)bInputstream.read())!=-1) {
count++;
}
String str=new String(bytes);
System.out.println(str);
}
}
在一个文件中写入信息
public class IOboutput {
static final String FilePath="src/exercise/IOboutput1.java";
public static void main(String[] args) throws IOException {
File file=new File(FilePath);
OutputStream outputstream=new FileOutputStream(file);
BufferedOutputStream boutputstream=new BufferedOutputStream(outputstream);
String str="123123";
boutputstream.write(str.getBytes());
boutputstream.close();
}
}
字节流与缓存流的代码看似并无太大差别,缓存流只不过比字节流多了Buffered,但在实际应用上缓存流的效率实际上远高于字节流
以上述代码为例,在src/exercise/exercise.java中书写了50000个*符号,利用System.currentTimeMillis()函数计算所需毫秒数,当用字节流读取文件时共用了971ms
而用缓存流时,只用了31ms