1 package 文件操作; 2 3 import java.io.File; 4 import java.io.FileOutputStream; 5 import java.io.IOException; 6 import java.io.OutputStream; 7 8 public class TestOutputStream { 9 public static void main(String[] args) throws IOException {10 File file=new File("D:"+File.separator+"test.txt");11 OutputStream outputStream=new FileOutputStream(file);12 String str="每天进步一点点!";13 byte[] bytes=str.getBytes();14 outputStream.write(bytes);15 outputStream.close();16 }17 }
1 package 文件操作; 2 3 import java.io.File; 4 import java.io.FileOutputStream; 5 import java.io.IOException; 6 import java.io.OutputStream; 7 8 public class TestOutputStream { 9 public static void main(String[] args) throws IOException {10 File file=new File("D:"+File.separator+"test.txt");11 OutputStream outputStream=new FileOutputStream(file);12 String str="让世界充满爱!";13 byte[] bytes=str.getBytes();14 15 // outputStream.write(bytes);16 17 for(byte b:bytes){18 outputStream.write(b);//单个字节输出19 }20 21 outputStream.close();22 }23 }
1 package 文件操作; 2 3 import java.io.File; 4 import java.io.FileOutputStream; 5 import java.io.IOException; 6 import java.io.OutputStream; 7 8 public class TestOutputStream { 9 public static void main(String[] args) throws IOException {10 File file=new File("D:"+File.separator+"test.txt");11 OutputStream outputStream=new FileOutputStream(file);12 String str="让世界充满爱!";13 byte[] bytes=str.getBytes();14 // outputStream.write(bytes, 1, 3);//这样输出中文会有乱码:檬?15 outputStream.write(bytes, 2, 4);//输出:世界16 outputStream.close();17 }18 }
1 package 文件操作; 2 3 import java.io.File; 4 import java.io.FileOutputStream; 5 import java.io.IOException; 6 import java.io.OutputStream; 7 8 public class TestOutputStream { 9 public static void main(String[] args) throws IOException {10 File file=new File("D:"+File.separator+"test.txt");11 OutputStream outputStream=new FileOutputStream(file,true);//文件内容追加,而不是覆盖。12 String str="让世界充满爱!";13 byte[] bytes=str.getBytes();14 outputStream.write(bytes);15 outputStream.close();16 }17 }
1 package 文件操作; 2 3 import java.io.File; 4 import java.io.FileOutputStream; 5 import java.io.IOException; 6 import java.io.OutputStream; 7 8 public class TestOutputStream { 9 public static void main(String[] args) throws IOException {10 File file=new File("D:"+File.separator+"test.txt");11 OutputStream outputStream=new FileOutputStream(file,true);//文件内容追加,而不是覆盖。12 String str="让世界充满爱!\r\n";//每次输出写回文件换行13 byte[] bytes=str.getBytes();14 outputStream.write(bytes);15 outputStream.close();16 }17 }
字节流可以不用关闭操作即可将内容写进文件。