***Reader 和 ****Writer
1.假设有一个txt文件,里面存放着大写、小写、数字,使用IO把文件内容统计出来,并打印输出。
写把文件都出来放到String里,再对String操作即可。
import java.io.*;
public class BufferTXTReader {
/**
* 假设有一个txt文件,里面存放着大写、小写、数字,使用IO把文件内容统计出来,并打印输出。
*
* @param filePath
*/
public static void readFileByBuffer(String filePath) throws IOException {
BufferedReader bufferedReader = new BufferedReader(new FileReader(filePath));
// BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(new FileInputStream(filePath)));
String value = "";
StringBuilder builder = new StringBuilder();
while ((value = bufferedReader.readLine()) != null) {
builder.append(value);
}
bufferedReader.close();
print(builder.toString());
}
public static void print(String result) {
char[] chars = result.toCharArray();
int count1 = 0;
int count2 = 0;
int count3 = 0;
for (int i = 0; i < chars.length; i++) {
char ch = chars[i];
if (ch >= 'A' && ch <= 'Z') {
count1++;
}
if (ch >= 'a' && ch <= 'z') {
count2++;
}
if (ch >= '0' && ch <= '9') {
count3++;
}
}
System.out.println(count1);
System.out.println(count2);
System.out.println(count3);
}
public static void main(String[] args) throws IOException {
readFileByBuffer("/Users/jack/Documents/cc.txt");
}
}
BufferedReader类和BufferedWriter类
1.拷贝文件:
2.从键盘写入字符串进文件
package com.judy.demo4;
import java.io.*;
public class MyReader {
MyReader() {
}
/**
* @param pathFrom 源
* @param pathTo 目标
* @throws IOException
*/
public void copyTxtFile(String pathFrom, String pathTo) throws IOException {
//创建两个可以传路径的 缓冲流 一个读 一个写
BufferedReader bufferedReader = new BufferedReader(new FileReader(pathFrom));
BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(pathTo));
String value = "";
while ((value = bufferedReader.readLine()) != null) { //整行读
bufferedWriter.write(value);
bufferedWriter.newLine(); //接收下一行
}
//关闭IO流
bufferedReader.close();
bufferedWriter.close();
}
/**
* @param input 键盘输入
* @param filePath 目标文件路径
* @throws IOException
*/
public void stringToFile(String input, String filePath) throws IOException {
StringReader stringReader = new StringReader(input);
BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(filePath));
int len = 0;
char[] chars = new char[10];
while ((len = stringReader.read(chars)) != -1) {
bufferedWriter.write(chars, 0, len);
}
stringReader.close();
bufferedWriter.close();
}
}
----------》用各种Reader子类和Writer子类都可以,输入输出成对出现。
如下例:
public static void copyFile2(String from, String to) throws IOException {
InputStreamReader reader = new InputStreamReader(new FileInputStream(from), Charset.forName("utf-8"));
OutputStreamWriter writer = new OutputStreamWriter(new FileOutputStream(to), Charset.forName("utf-8"));
int len = 0;
char[] ch = new char[10];
while ((len = reader.read(ch)) != -1) {
writer.write(ch, 0, len);
}
reader.close();
writer.close();
}
public static void copyFile3(String from, String to) throws IOException {
FileReader reader = new FileReader(from);
FileWriter writer = new FileWriter(to);
int len = 0;
char[] ch = new char[10];
//reader 调用的是父类的方法
while ((len = reader.read(ch)) != -1) {
writer.write(ch, 0, len);
}
reader.close();
writer.close();
}
测试类:
package com.judy.demo4;
import java.io.IOException;
import java.util.Scanner;
public class ReaderTest {
public static void main(String[] args) throws IOException {
Scanner scanner = new Scanner(System.in);
String input = scanner.nextLine();
MyReader myReader = new MyReader();
myReader.copyTxtFile("D:\\aa.txt", "D:\\bb.txt");
myReader.stringToFile(input, "D:\\aa.txt");
}
}
缓冲流Buffered**** - -------------------》对文件操作提高效率
1.拷贝文件
2.把字节追加到问价末尾
package com.judy.demo5;
import java.io.*;
public class BufferedClass {
BufferedClass() {
}
/**
* @param fromPath 源文件路径 "D:\\mine.doc"
* @param toPath 目标文件路径 "D:\\myfile\\mycopy.doc"
* @throws IOException
*/
public void copyFileUseBuffered(String fromPath, String toPath) throws IOException {
BufferedInputStream bufferedInputStream = new BufferedInputStream(new FileInputStream(fromPath));
BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(new FileOutputStream(toPath));
int len = 0;
byte[] bytes = new byte[20];
while ((len = bufferedInputStream.read(bytes)) != -1) {
bufferedOutputStream.write(bytes, 0, len);
}
bufferedInputStream.close();
bufferedOutputStream.close();
}
/**
* 往文件末尾添加字符串
*
* @param filePath 文件路径 "D:\\aa.txt"
* @param str 需要追加的字符串 " forever"
* @throws IOException
*/
public void appendByOutputStream(String filePath, String str) throws IOException {
File file = new File(filePath);
//append为true 则把字节追加到文件末尾,也就是可以往文件写进内容了,而写进的内容是追加在末尾的
FileOutputStream fileOutputStream = new FileOutputStream(file, true);
byte[] bytes = str.getBytes();
fileOutputStream.write(bytes, 0, bytes.length);
fileOutputStream.close();
}
}
测试:
package com.judy.demo5;
import java.io.IOException;
public class BufferedTest {
public static void main(String[] args) throws IOException {
BufferedClass bufferedClass = new BufferedClass();
bufferedClass.copyFileUseBuffered("D:\\mine.doc", "D:\\myfile\\mycopy.doc");
bufferedClass.appendByOutputStream("D:\\aa.txt", " forever");
}
}
RandomAccessFile类
这个类可以对文件指定位置之后进行操作。
1.输出指向索引10位置之后的内容
package com.judy.demo6;
import java.io.IOException;
import java.io.RandomAccessFile;
public class RandomFile {
RandomFile() {
}
/**
* @param filePath 需要操作的文件路径
* @throws IOException
*/
public static void randomReadFile(String filePath) throws IOException {
//mode 操作的模式:rw 可读可写,还有其他可选模式,查API文档即可。
RandomAccessFile randomAccessFile = new RandomAccessFile(filePath, "rw");
System.out.println(randomAccessFile.getFilePointer());
//从该位置开始执行操作
randomAccessFile.seek(10);
//获取文件内容指针的位置
System.out.println(randomAccessFile.getFilePointer());
String result = randomAccessFile.readLine();
System.out.println(result);
randomAccessFile.close();
}
public static void main(String[] args) throws IOException {
randomReadFile("D:\\aa.txt");
}
}
属性文件.properties 和对应操作它的Properties类
配合Hashtable <k,v>集合使用,可以将需要的内容(自定义的内容且有序)存储到.properties文件中
UUID产生随机数,差API看范围和用法。
package com.judy.properties;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Hashtable;
import java.util.Map;
import java.util.Properties;
import java.util.UUID;
public class PropertiesUtils {
PropertiesUtils() {
}
public void storeHashTableToFile(Hashtable<String, String> hashtable, String filePath) throws IOException {
File file = new File(filePath);
if (!file.exists()) {
file.mkdirs();
}
Properties properties = new Properties();
//存进文件的路径
FileOutputStream fileOutputStream = new FileOutputStream(file.getAbsolutePath() + File.separator + getRandomFileName() + ".properties");
//循环把hashtable的内容存进.properties文件中
for (Map.Entry<String, String> mapEntry : hashtable.entrySet()) { //遍历Hashtable用Map.entry
//放入properties
properties.setProperty(mapEntry.getKey(), mapEntry.getValue());
}
properties.store(fileOutputStream, "this is a student record");
fileOutputStream.close();
}
/**
* 产生一个包含数字和字母的随机文件名
*
* @retrun
*/
public String getRandomFileName() {
return UUID.randomUUID().toString().replaceAll("-", "").substring(0, 20);
}
}
测试类:
package com.judy.properties;
import java.io.IOException;
import java.util.Hashtable;
public class PropertiesTest {
public static void main(String[] args) throws IOException {
Hashtable<String, String> hashtable = new Hashtable<>();
hashtable.put("name", "judy");
hashtable.put("age", "20");
hashtable.put("address", "北京");
PropertiesUtils propertiesUtils = new PropertiesUtils();
propertiesUtils.storeHashTableToFile(hashtable, "D:\\test.doc");
}
}