您的位置:首页 > 编程语言 > Java开发

java--File的读取和写入实例

2013-10-10 14:48 393 查看
实例来源think in java

读取:

根据需要读取文件返回不同类型的信息进行选择使用。

实例1

使用BufferReader读取。

package io;

// 使用Reader方式进行读取
import java.io.*;

public class BufferedInputFile {
// Throw exceptions to console:
public static String read(String filename) throws IOException {
// 使用BufferedReader进行缓冲,来提高文件的读取数据
BufferedReader in = new BufferedReader(new FileReader(filename));
String s;
StringBuilder sb = new StringBuilder();
while ((s = in.readLine()) != null)
sb.append(s + "\n");
in.close();
return sb.toString();
}

public static void main(String[] args) throws IOException {
System.out.print(read("C:\\Users\\zm\\workspace\\Thinking in java\\src\\io\\BufferedInputFile.java"));
}
}


实例2

使用StringReader类读取,in.read()以int形式返回下一个字节。

package io;

// 从内存中读取
import java.io.*;

public class MemoryInput {
public static void main(String[] args) throws IOException {
StringReader in = new StringReader(BufferedInputFile
.read("C:\\Users\\zm\\workspace\\Thinking in java\\src\\io\\MemoryInput.java"));
int c;
while ((c = in.read()) != -1)
System.out.print((char) c);
}
}


实例3

使用DataInputStream类读取,in.readByte()返回的byte类型。

package io;

//相对TestEOF.java 此方法不能检测字节是否结束
//面向字节的IO类
import java.io.*;

public class FormattedMemoryInput {
public static void main(String[] args) throws IOException {
try {
DataInputStream in = new DataInputStream(
new ByteArrayInputStream(BufferedInputFile
.read("C:\\Users\\zm\\workspace\\Thinking in java\\src\\io\\FormattedMemoryInput.java")
.getBytes()));
while (true)
System.out.print((char) in.readByte());
} catch (EOFException e) {
System.err.println("End of stream");
}
}
}

另一种用法,差异在第9行,使用in.available() != 0,判断检测字节是否结束。

FormattedMemoryInput例子在运行时 不能检测流中是否还有字节,所以在控制台最后会抛出一个异常:End of stream

下面用法可以避免此问题。

package io;

import java.io.*;

public class TestEOF {
public static void main(String[] args) throws IOException {
DataInputStream in = new DataInputStream(new BufferedInputStream(
new FileInputStream("C:\\Users\\zm\\workspace\\Thinking in java\\src\\io\\TestEOF.java")));
while (in.available() != 0)
System.out.print((char) in.readByte());
}
}


写:


实例1

基本的文件写入

package io;

// 基本的文件输出
import java.io.*;

public class BasicFileOutput {
static String file = "C:\\Users\\zm\\workspace\\Thinking in java\\src\\io\\BasicFileOutput.out";

public static void main(String[] args) throws IOException {
BufferedReader in = new BufferedReader(
new StringReader(
BufferedInputFile.read("C:\\Users\\zm\\workspace\\Thinking in java\\src\\io\\BasicFileOutput.java")));
PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(
file)));
int lineCount = 1;
String s;
while ((s = in.readLine()) != null)
out.println(lineCount++ + ": " + s);
out.close();
// Show the stored file:
System.out.println(BufferedInputFile.read(file));
}
}

快捷用法,PrintWriter提供了进行缓存操作构造函数,省去了我们自己进行包装。

package io;

// 输出方式的快捷用法,PrintWriter提供了进行缓存操作构造函数
import java.io.*;

public class FileOutputShortcut {
static String file = "C:\\Users\\zm\\workspace\\Thinking in java\\src\\io\\FileOutputShortcut.out";

public static void main(String[] args) throws IOException {
BufferedReader in = new BufferedReader(new StringReader(
BufferedInputFile.read("C:\\Users\\zm\\workspace\\Thinking in java\\src\\io\\FileOutputShortcut.java")));
// Here's the shortcut:
PrintWriter out = new PrintWriter(file);
int lineCount = 1;
String s;
while ((s = in.readLine()) != null)
out.println(lineCount++ + ": " + s);
out.close();
// Show the stored file:
System.out.println(BufferedInputFile.read(file));
}
}


读取和写入工具类

//: net/mindview/util/TextFile.java
// Static functions for reading and writing text files as
// a single string, and treating a file as an ArrayList.
package net.mindview.util;

import java.io.*;
import java.util.*;

public class TextFile extends ArrayList<String> {
private static String gpfile = "C:\\Users\\zm\\workspace\\Thinking in java\\src\\net\\mindview\\util\\";
// Read a file as a single string:
public static String read(String fileName) {
StringBuilder sb = new StringBuilder();
try {
BufferedReader in = new BufferedReader(new FileReader(new File(
fileName).getAbsoluteFile()));
try {
String s;
while ((s = in.readLine()) != null) {
sb.append(s);
sb.append("\n");
}
} finally {
in.close();
}
} catch (IOException e) {
throw new RuntimeException(e);
}
return sb.toString();
}

// Write a single file in one method call:
public static void write(String fileName, String text) {
try {
PrintWriter out = new PrintWriter(new File(fileName)
.getAbsoluteFile());
try {
out.print(text);
} finally {
out.close();
}
} catch (IOException e) {
throw new RuntimeException(e);
}
}

// Read a file, split by any regular expression:
public TextFile(String fileName, String splitter) {
super(Arrays.asList(read(fileName).split(splitter)));
// Regular expression split() often leaves an empty
// String at the first position:
if (get(0).equals(""))
remove(0);
}

// Normally read by lines:
public TextFile(String fileName) {
this(fileName, "\n");
}

public void write(String fileName) {
try {
PrintWriter out = new PrintWriter(new File(fileName)
.getAbsoluteFile());
try {
for (String item : this)
out.println(item);
} finally {
out.close();
}
} catch (IOException e) {
throw new RuntimeException(e);
}
}

// Simple test:
public static void main(String[] args) {
String file = read(gpfile + "TextFile.java");
write("d:\\test.txt", file);
TextFile text = new TextFile("d:\\test.txt");
text.write("d:\\test2.txt");
// Break into unique sorted list of words:
TreeSet<String> words = new TreeSet<String>(new TextFile(
gpfile + "TextFile.java", "\\W+"));
// Display the capitalized words:
System.out.println(words.headSet("a"));
}
}



内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: