有了这些,java IO就不愁了

IO的总结:

  • java中相对路径和绝对路径的问题:
    • 在web项目中,如果生成的文件前面没有 / 开头的话,表示的是生成的文件在当前项目的根目录下如student.txt在项目中刷新就能看到。
    • 如果是以/开头的话,如/student.txt则表示文件存放在磁盘根目录下(D://student.txt)。(好像也有可能在eclipse的根目录下)
    • 也可以将文件写在绝对路径下,如C://user/student.txt则表示文件在C盘的user目录下。

1. 基本流: InputStream、OutputStream、Reader、Writer等基本的输入输出,在使用的时候通过这些抽象方法的实现类(FileInputStream、FileOutputStream、FileReader、FileWriter)等来进行读取的读取和写入主要是通过 int b = fis.read() 或fos.write(b) 这种方式来读取或者写入的。

2. BufferedInputStream、BufferedOutputStream、BufferedReader、BufferedWriter等带有Buffer关键字的,通常情况下是在1的情况下再套一层Buffer流,原理就是先将数据写入到缓存中,再从缓存中将数据取出来。

  • Buffer读取流的时候,使用的是bis.Reader()来读取的而BufferedReader则是使用br.readLine()来读取一行。
  • 当使用BufferedWriter来写入数据的时候有一个bw.flush()方法,主要目的是将缓存中的数据强制写出去。

3. Data流: 主要是可以对基本数据类型进行写入写出等操作

  • Data流写数据:
    创建一个字节数组输出流 ByteArrayOutputStream。
    创建 DataOutputStream 对象来对ByteArrayOutputStream进行数据的写入操作。
    可通过 dos.writeBoolean() writeString() writeDouble() ... 。
  • Data流读数据:
    创建一个字节数组输入流 ByteArrayInputStream();
    创建 DataInputStream对象来对上述字节流读取。
    可以通过dis.readBoolean() readString() ....

4. Print流: 常见的是System.out.print()来输出

  • PrintStream可以指定输出对象,并不一定要输出在控制台,可以输出在文件中等。
    创建输出文件(FileOutputStream fos = new FileOutputStream("txt/unicode.txt");)、设置输出位置(System.setOut(ps);)、打印输出对象(System.out.println(i);)即可完成指定输出。
  • PrintWriter对象,可以指定将数据输出到文件中。
  • 使用PrintStream读取文件数据。

5. ObjectOutputStream/ObjectInputStream 利用这两个对象可以存放序列化的数据。

6. 随机读取File文件:RandomAccessFile提供了seek()方法,用来定位将要读写文件的指针位置,我们也可以通过调用getFilePointer()方法来获取当前指针的位置。

7. 管道:管道主要用来实现同一个虚拟机中的两个线程进行交流。因此,一个管道既可以作为数据源媒介也可作为目标媒介。需要注意的是java中的管道和Unix/Linux中的管道含义并不一样,在Unix/Linux中管道可以作为两个位于不同空间进程通信的媒介,而在java中,管道只能为同一个JVM进程中的不同线程进行通信。和管道相关的IO类为:PipedInputStream和PipedOutputStream。

1.文件输入输出流

/* 使用文件输入输出流的方式将sa图片输出到另一个位置*/
public class Test1FileInputStream {
private static FileInputStream in = null;
private static FileOutputStream out = null;

public static void main(String[] args) {

int b = 0;

try {
in = new FileInputStream("pic/sa.jpg");
out = new FileOutputStream("output/pic/sb.jpg");

while ((b = in.read()) != -1) {
System.out.print((char) b);
out.write(b);
}

in.close();
out.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
System.out.println("over");
}

}
}

2.文件读取类

/从文件中读取数据/
public class Test3FileReader {

public static void main(String[] args) {

int c = 0;
try {
FileReader reader = new FileReader("a.txt");
while ((c = reader.read()) != -1) {
System.out.print((char) c);
}
} catch (Exception e) {
e.printStackTrace();
}

}

}

3.文件写入类

/* 将数据写入文本中*/
public class Test4FileWriter {

public static void main(String[] args) {
try {
FileWriter writer = new FileWriter("a.txt");
for (int i = 0; i < 65535; i++) {
writer.write((char) i);
}
writer.close();
System.out.println("success");
} catch (IOException e) {
e.printStackTrace();
System.out.println("err");
System.exit(-1);
}

}

}

4.使用流的方式读取文件

/读取并输出文件内容/
public class Test5BufferStream {
public static void main(String[] args) {

try {
FileInputStream inputStream = new FileInputStream("mark.log");
BufferedInputStream bis = new BufferedInputStream(inputStream);
// System.out.println(bis.read());
// System.out.println(bis.read());
int c = 0;
while ((c = bis.read()) != -1) {
System.out.print((char) c);
}
bis.close();
} catch (Exception e) {
e.printStackTrace();
}

}
}

5.使用缓存的方式读取和写入文件

/向一个文件中写入缓存数据并读取出来/
public class Test6BufferStream1 {

public static void main(String[] args) {

try {
// 通过缓存区向文件中写入数据
BufferedWriter bw = new BufferedWriter(new FileWriter("txt/a.txt"));
String s = null;
for (int i = 0; i < 100; i++) {
s = String.valueOf(Math.random());
bw.write(s);
bw.newLine();
}
bw.flush();

// 从文件中将数据读取到缓冲区在读取出来
BufferedReader br = new BufferedReader(new FileReader("txt/a.txt"));
while ((s = br.readLine()) != null) {
System.out.println(s);
}
bw.close();
br.close();

} catch (IOException e) {
e.printStackTrace();
}

}

}

6.将输入的内容打印出来

/将数据从console中读出/
public class Test7TransForm {
public static void main(String[] args) {

InputStreamReader reader = new InputStreamReader(System.in);
BufferedReader reader2 = new BufferedReader(reader);

String s = null;

try {
s = reader2.readLine();
while (s != null) {
if (s.equalsIgnoreCase("exit")) {
System.exit(0);
}
System.out.println(s);
s = reader2.readLine();
}
reader2.close();
reader.close();
} catch (IOException e) {
e.printStackTrace();
}

}
}

7.使用OutputStreamWriter类将数据写入到文件中

/OutputStreamWriter类/
public class Test8TransForm1 {

public static void main(String[] args) {
try {
// 如果为true表示在原来的基础上追加 数据而不是覆盖
OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream("txt/b.txt", true), "utf-8");
osw.write("abcdefghijklmnopqrst ");
osw.flush();// 将缓存中的数据强制发送出去
System.out.println(osw.getEncoding());

osw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}

8.ByteArrayOutputStream类

/利用dataStream可以向文件中写入各种类型的数据/
public class Test9DataStream {

public static void main(String[] args) throws IOException {

// 创建字节数组
ByteArrayOutputStream baos = new ByteArrayOutputStream();
// 创建数据输出流
DataOutputStream dos = new DataOutputStream(baos);

dos.writeDouble(Math.random());
dos.writeBoolean(true);
ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
System.out.println(bais.available());// 八个字节
DataInputStream dis = new DataInputStream(bais);
System.out.println(dis.readDouble());
System.out.println(dis.readBoolean());
dos.close();
dis.close();

}

}

9.使用PrintStream将数据输出到文件中

/将输出输出到文件中/
public class TestPrintStream1 {

private static PrintStream ps = null;

public static void main(String[] args) throws Exception {
// 创建输出的文件
FileOutputStream fos = new FileOutputStream("txt/unicode.txt");
// 创建输出流
ps = new PrintStream(fos);

if (ps != null) {
// 指定输出的位置
System.setOut(ps);
}
int in = 0;
// 将数据输出
for (char i = 0; i < 60000; i++) {
System.out.print(i + " ");
in++;
if (in >= 50) {
System.out.println();
in = 0;
}
}
System.out.println("over");
}

}

10.日志的基本原理

/将输入的内容记录到日志中/
public class TestPrintStream2 {

public static void main(String[] args) throws Exception {

BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String s = null;

FileWriter writer = new FileWriter("mark.log", true);

PrintWriter log = new PrintWriter(writer);
while ((s = br.readLine()) != null) {
if (s.equalsIgnoreCase("exit")) {
break;
}
System.out.println(s);
log.println("--------------");
log.println(s);
log.flush();
}
log.print("" + new Date() + "");
log.flush();
log.close();
}

}

11.使用缓存区文件读取

/使用输出流读取文件内容,显示在console中/
public class TestPrintStream3 {

public static void main(String[] args) {
String fileName = "mark.log";
if (fileName != null) {
list(fileName, System.out);
}
}

private static void list(String file, PrintStream ps) {

try {
// 创建缓冲区读取对象
BufferedReader br = new BufferedReader(new FileReader(file));
String s = null;
// 循环读取缓冲区的内容
while ((s = br.readLine()) != null) {
// 将数据读取到控制台上
ps.println(s);
}
br.close();
} catch (Exception e) {
e.printStackTrace();
ps.print("读取错误");
}
}

}

12.对象输入输出流

/* transient 修饰的成员变量在序列化的时候不予考虑*/
public class TestObjectIO {
public static void main(String[] args) {
T t = new T();
t.i = 6;
try {
// 将对象写到文本中
FileOutputStream fos = new FileOutputStream("txt/object.io");
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(t);
oos.flush();
oos.close();

// 将对象从文本中读出来
FileInputStream fis = new FileInputStream("txt/object.io");
ObjectInputStream ois = new ObjectInputStream(fis);
T t1 = (T) ois.readObject();
System.out.println(t1.d + " " + t1.i + " " + t1.j + " " + t1.k);

} catch (Exception e) {
e.printStackTrace();
}

}
}

class T implements Serializable {
double d = 2.3;
int i = 10;
int j = 9;
transient int k = 2;
}

13. 随机读写

/随机读写文件/
public class TestAccessFile {

public static void randomAccessFileWrite() throws IOException {
// 创建一个RandomAccessFile对象
RandomAccessFile file = new RandomAccessFile("d:/test.txt", "rw");
// 通过seek方法来移动读写位置的指针
file.seek(10);
// 获取当前指针
long pointerBegin = file.getFilePointer();
// 从当前指针位置开始写
file.write("hehe 你好牛鞭".getBytes());
long pointerEnd = file.getFilePointer();
System.out.println("pointerBegin:" + pointerBegin + "\n" + "pointerEnd:" + pointerEnd + "\n");
file.close();
}

public static void randomAccessFileRead() throws IOException {
// 创建一个RandomAccessFile对象
RandomAccessFile file = new RandomAccessFile("d:/test.txt", "rw");
// 通过seek方法来移动读写位置的指针
file.seek(10);
// 获取当前指针
long pointerBegin = file.getFilePointer();
// 从当前指针开始读
byte[] contents = new byte[1024];
file.read(contents);
long pointerEnd = file.getFilePointer();
System.out.println(
"pointerBegin:" + pointerBegin + "\n" + "pointerEnd:" + pointerEnd + "\n" + new String(contents));
file.close();
}

public static void main(String[] args) throws Exception {

randomAccessFileWrite();
randomAccessFileRead();
}

}

14. 管道Demo

public class TestPipe {

public static void main(String[] args) throws IOException {
// 实现在不同线程中对同一对象进行读写操作
final PipedOutputStream pos = new PipedOutputStream();
final PipedInputStream pis = new PipedInputStream(pos);

// 在第一个线程中对管道进行写入操作
Thread t1 = new Thread(new Runnable() {
@Override
public void run() {
try {
pos.write("Hello world, pipe!".getBytes());
} catch (IOException e) {
}
}
});

// 在第二个线程中对管道数据进行读取操作
Thread t2 = new Thread(new Runnable() {
@Override
public void run() {
try {
int data = pis.read();
while (data != -1) {
System.out.print((char) data);
data = pis.read();
}
} catch (IOException e) {
} finally {
try {
pis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
});
t1.start();
t2.start();
}
}

posted @ 2017-09-14 19:49  esileme  阅读(222)  评论(0)    收藏  举报