字符流
文件字符输入流(FileReader)
import java.io.FileReader;
import java.io.Reader;
public class Test {
public static void main(String[] args) {
try (
Reader inputStream = new FileReader("E:/Desktop/temp.txt");
) {
int c;
while ((c = inputStream.read()) != -1) {
System.out.print((char) c);
}
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
import java.io.FileReader;
import java.io.Reader;
public class Test {
public static void main(String[] args) {
try (
Reader inputStream = new FileReader("E:/Desktop/temp.txt");
) {
char[] buffer = new char[3];
int len;
while ((len = inputStream.read(buffer)) != -1) {
String s = new String(buffer, 0, len);
System.out.print(s);
}
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
文件字符输出流(FileWriter)
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
public class Test {
public static void main(String[] args) {
try (
Writer fw = new FileWriter("E:/Desktop/temp.txt", true);
) {
fw.write('a');
fw.write(97);
fw.write('王');
fw.write("\r\n");
fw.write("哈哈哈abc");
fw.write("我爱你abc", 0, 3);
fw.write("\r\n");
char[] buffer = {'我', '们', '都', '是', '追', '梦', '人'};
fw.write(buffer);
fw.write(buffer, 0, 2);
fw.write("\r\n");
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
import java.io.FileWriter;
import java.io.Writer;
public class Test {
public static void main(String[] args) throws Exception {
Writer fw = new FileWriter("E:/Desktop/temp.txt");
fw.write('a');
fw.write('b');
fw.write('c');
fw.write("\r\n");
fw.write("我们都是追梦人");
fw.write("\r\n");
fw.flush();
fw.write("还能继续写下去");
fw.flush();
fw.close();
}
}