package demo;
import java.io.*;
public class TestStream{
//先建一个空文件供我们操作
public void createFile()throws Exception{
File file = new File("test.txt");
file.createNewFile();
}
//初始化块,先把文件给建了
{
try{
createFile();
}catch(Exception e){
e.printStackTrace();
}
}
//测试程序把内容写入文件
public void testWrite()throws Exception{
OutputStream os = new FileOutputStream("test.txt");
String str = "hello world";
//String的getBytes方法可以把字符串变成一个字节数组
os.write(str.getBytes());
//释放资源
os.close();
}
// GBK GB2312
//使用FileInputStream把test.txt的文件内容读取出来,并打印到控制台
public void testRead()throws Exception{
FileInputStream input = new FileInputStream("test.txt");
int a = input.read();
while(a != -1){
System.out.println((char)a);
a = input.read();
}
input.close();
}
public static void main(String[] args)throws Exception{
TestStream t = new TestStream();
//t.testWrite();
t.testRead();
}
}
import java.io.*;
public class TestStream{
//先建一个空文件供我们操作
public void createFile()throws Exception{
File file = new File("test.txt");
file.createNewFile();
}
//初始化块,先把文件给建了
{
try{
createFile();
}catch(Exception e){
e.printStackTrace();
}
}
//测试程序把内容写入文件
public void testWrite()throws Exception{
OutputStream os = new FileOutputStream("test.txt");
String str = "hello world";
//String的getBytes方法可以把字符串变成一个字节数组
os.write(str.getBytes());
//释放资源
os.close();
}
// GBK GB2312
//使用FileInputStream把test.txt的文件内容读取出来,并打印到控制台
public void testRead()throws Exception{
FileInputStream input = new FileInputStream("test.txt");
int a = input.read();
while(a != -1){
System.out.println((char)a);
a = input.read();
}
input.close();
}
public static void main(String[] args)throws Exception{
TestStream t = new TestStream();
//t.testWrite();
t.testRead();
}
}