java IO操做:FileInputStream,FileOutputStream,FileReader,FileWriter實例
FileInputStreamjava
- <span style="font-family:Verdana;">import java.io.File;
- import java.io.FileInputStream;
- import java.io.InputStream;
-
- public class TestFileInputStream {
- public static void main(String[] args) throws Exception {
-
- File f = new File("c:" + File.separator + "test.txt");
-
- InputStream input = null;
-
- input = new FileInputStream(f);
-
- byte b[] = new byte[1024];
- int len = input.read(b);
-
- input.close();
-
- System.out.println("讀入數據的長度:" + len);
- System.out.println("內容爲:" + new String(b, 0, len));
- }
- }</span>
FileOutputStream數組
- <span style="font-family:Verdana;">import java.io.File;
- import java.io.FileOutputStream;
- import java.io.OutputStream;
-
- public class TestFileOutputStream {
- public static void main(String[] args) throws Exception {
-
- File f = new File("c:" + File.separator + "test.txt");
-
- OutputStream out = null;
-
- out = new FileOutputStream(f);
-
- String str = "Hello World!!!";
-
- byte b[] = str.getBytes();
-
- out.write(b);
-
- out.close();
- }
- }</span>
FileReaderspa
- <span style="font-family:Verdana;">import java.io.File;
- import java.io.FileReader;
- import java.io.Reader;
-
- public class TestFileReader {
- public static void main(String[] args) throws Exception {
-
- File f = new File("d:" + File.separator + "test.txt");
-
- Reader reader = null;
-
- reader = new FileReader(f);
-
- char c[] = new char[1024];
- int len = reader.read(c);
-
- reader.close();
-
- System.out.println("內容爲:" + new String(c, 0, len));
- }
- }</span>
FileWriter對象
- <span style="font-family:Verdana;">import java.io.File;
- import java.io.FileWriter;
- import java.io.Writer;
-
- public class TestFileWriter {
- public static void main(String[] args) throws Exception {
-
- File f = new File("c:" + File.separator + "test.txt");
-
- Writer out = null;
-
- out = new FileWriter(f);
-
- String str = "Hello World!!!";
- out.write(str);
- out.flush();
-
- out.close();
- }
- }</span>
歡迎關注本站公眾號,獲取更多信息