IO源读写txt中存储的文字信息和图片信息
IO流读写txt中存储的文字信息和图片信息
前几天遇到了用IO流读取txt(或其它类型文件)是中存储的文字信息和图片信息,在网上找了很久都没有找到想要的答案。今天终于把这个问题解决了,拿出来跟大家分享下,希望对有同样需求的大虾们有所帮助!不过最后还有点疑问,因为是用的二进制流读取的文字和图片信息,图片信息是以“END”结束的,现在的问题是怎么读到“END”就中止图片的读取?
前几天遇到了用IO流读取txt(或其它类型文件)是中存储的文字信息和图片信息,在网上找了很久都没有找到想要的答案。今天终于把这个问题解决了,拿出来跟大家分享下,希望对有同样需求的大虾们有所帮助!不过最后还有点疑问,因为是用的二进制流读取的文字和图片信息,图片信息是以“END”结束的,现在的问题是怎么读到“END”就中止图片的读取?
public class Test { static File save = new File("save.txt"); /** * @param args * @throws IOException */ public static void main(String[] args) throws IOException { test1(); test2(); test3(); } //把文字信息写进TXT文件中 public static void test1() throws IOException { if (!save.exists()) save.createNewFile(); FileOutputStream output = new FileOutputStream(save); OutputStreamWriter output_writer = new OutputStreamWriter(output); PrintWriter pr = new PrintWriter(output_writer); pr.print(new Date()); pr.print("==============img"); pr.flush(); pr.close(); output_writer.close(); output.close(); } //把图片信息写进TXT文件中(在文字信息之后写) public static void test2() throws IOException { File file = new File("1.bmp"); if (!save.exists()) save.createNewFile(); FileInputStream input_stream = new FileInputStream(file); FileOutputStream out_stream = new FileOutputStream(save, true); int len = 0; byte[] bytes = new byte[1024]; while (-1 != (len = input_stream.read(bytes))) { out_stream.write(bytes, 0, len); } out_stream.close(); input_stream.close(); } //分别读去文字信息及图片信息 public static void test3() throws IOException { FileInputStream input = new FileInputStream(save); File temp = new File("temp.bmp"); if (!temp.exists()) temp.createNewFile(); FileOutputStream output = new FileOutputStream(temp); byte[] bytes = new byte[1]; int len = 0; while (-1 != (len = input.read(bytes))) { String temp1 = new String(bytes); System.out.println(temp1); if ("g".equals(temp1))//以g结束文字信息的读取 break; } byte[] bytes1 = new byte[1024]; int len1 = 0; //开始读取图片信息 while (-1 != (len1 = input.read(bytes1))) { output.write(bytes1, 0, len1); } output.close(); input.close(); } }