基础题
练习一
字节输出流写出字节数据
描述:利用字节输出流一次写一个字节的方式,向D盘的a.txt文件输出字符‘a’。
/**
*
*/
package Test;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
/**
* @author sq
* @date 2020年5月26日
* @Desription: TODO
*/
public class Test1 {
public static void main(String[] args) throws IOException {
try {
FileOutputStream file=new FileOutputStream("d:\\a.txt"); // 创建输入流,指定位置
file.write(97); // 写入ascii表97等于
file.close(); // 关闭数入流,节约资源
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
练习二
字节输出流写出字节数组数据
描述:利用字节输出流一次写一个字节数组的方式向D盘的b.txt文件输出内容:“i love java”。
/**
*
*/
package Test;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
/**
* @author sq
* @date 2020年5月26日
* @Desription: TODO
*/
public class Test2 {
public static void main(String[] args) throws IOException {
// 抛出io流异常
FileOutputStream fileOut=new FileOutputStream("d:\\a.txt"); // 输出流,指定位置
byte[] by= "I Love Java".getBytes(); // 将字符串转化为字节数组
fileOut.write(by); // 写入字节
fileOut.close(); // 关闭io流
}
}
练习三
文件的续写和换行输出
描述:在D盘下,有一c.txt 文件中内容为:HelloWorld 在c.txt文件原内容基础上,添加五句 I love java,而且要实现一句一行操作(注:原文不可覆盖)。
利用字节输出流对象往C盘下c.txt文件输出5句:”i love java”
/**
*
*/
package Test;
import java.io.FileOutputStream;
/**
* @author sq
* @date 2020年5月26日
* @Desription: TODO
*/
public class Test3 {
public static void main(String[] args)throws Exception {
FileOutputStream fileO=new FileOutputStream("d:\\c.txt",true); // 传入指定位置,true不重写原文内容
String zifu="I Love Java\r";// \n和\r都表示换行
for (int i = 0; i < 5; i++) {
// 循环五次加入
System.out.println(zifu);
fileO.write(zifu.getBytes()); // 将字符串转化为字节
}
fileO.close(); // 关闭流
}
}
练习四
字节输入流一次读取一个字节数据
描述:利用字节输入流读取D盘文件a.txt的内容,文件内容确定都为纯ASCII字符,使用循环读取,一次读取一个字节,直到读取到文件末尾。将读取的字节输出到控制台
/**
*
*/
package Test;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
/**
* @author sq
* @date 2020年5月26日
* @Desription: TODO
*/
public class Test4 {
public static void main(String[] args) throws IOException {
FileInputStream fileI=new FileInputStream("d:\\a.txt"); // 创建输入流将txt的文件输入到java的控制台
int len=-