1. Open the file in Java
This example uses the read(buffer) method of FileInputStream to read 512 bytes from the source program file OpenFile.java each time and store In the buffer buffer, the string newString(buffer) constructed from the value in the buffer is displayed on the screen. The program is as follows:
importjava.io.*; publicclassOpenFile { publicstaticvoidmain(Stringargs[])throwsIOException { try {//创建文件输入流对象 FileInputStreamrf=newFileInputStream("OpenFile.java"); intn=512; bytebuffer[]=newbyte[n]; while((rf.read(buffer,0,n)!=-1)&&(n>0))//读取输入流 { System.out.print(newString(buffer)); } System.out.println(); rf.close();//关闭输入流 } catch(IOExceptionioe) { System.out.println(ioe); } catch(Exceptione) { System.out.println(e); } } }
2, Java language writing file
This example uses System.in.read(buffer) to input a line from the keyboard Characters are stored in the buffer buffer, and then the write(buffer) method of FileOutStream is used to write the contents of the buffer to the file Write1.txt. The procedure is as follows:
importjava.io.*; publicclassWrite1 { publicstaticvoidmain(Stringargs[]) { try { System.out.print("Input:"); intcount,n=512; bytebuffer[]=newbyte[n]; count=System.in.read(buffer);//读取标准输入流 FileOutputStreamwf=newFileOutputStream("Write1.txt"); //创建文件输出流对象 wf.write(buffer,0,count);//写入输出流 wf.close();//关闭输出流 System.out.println("SavetoWrite1.txt!"); } catch(IOExceptionioe) { System.out.println(ioe); } catch(Exceptione) { System.out.println(e); } } }
The above is the detailed content of How to open and write files using Java language. For more information, please follow other related articles on the PHP Chinese website!