package outputstream;
import org.testng.annotations.Test;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
/**
* 使用FileoutputStream将数据写到文件中,如果文件不存在就创建文件.前提是目录要存在
*/
public class fileoutpustream {
public static void main(String[] args) {
}
@Test
//单独写一个字符
public void m1() throws IOException {
String Path = "D:\\学习\\Java学习\\IO\\Test.txt";
FileOutputStream fileOutputStream = new FileOutputStream(Path);
try {
//注意,如果写入的是一个整数数字,实际存入的是对应ascall码的字符,想要存数字就以字符串的形式存比如:"1"
fileOutputStream.write('a');
} catch (IOException e) {
e.printStackTrace();
} finally {
fileOutputStream.close();
}
}
@Test
//使用String的getBytes方法
public void m2() throws IOException {
String Path = "D:\\学习\\Java学习\\IO\\Test.txt";
FileOutputStream fileOutputStream = new FileOutputStream(Path);
try {
String str = "hello,world~!";
fileOutputStream.write(str.getBytes());
} catch (IOException e) {
e.printStackTrace();
} finally {
fileOutputStream.close();
}
}
@Test
//使用FileOutputStream的write(字节数组)的方式
public void m3() throws IOException {
String Path = "D:\\学习\\Java学习\\IO\\Test.txt";
FileOutputStream fileOutputStream = new FileOutputStream(Path);
try {
String str = "hello,world~!!";
fileOutputStream.write(str.getBytes(),0,str.length());
} catch (IOException e) {
e.printStackTrace();
} finally {
fileOutputStream.close();
}
}
}
FileOutputStream的三种写出方式
最新推荐文章于 2024-03-11 22:36:08 发布