像我们经常会遇到这样的事情,例如一个txt文件中有姓名和电话,这个时候很经常就需要将名字和电话号码进行提取操作,这个时候就可以利用Java中io来实现了。

这里我就不具体介绍io中的字节流和字符流的异同点了,有兴趣的同学可以自己百度百度。

今天主要是介绍一下如何实现对文件内容的获取还有就是对获取的文件内容进行修改操作。下面看具体案例介绍。

Java中对文件的读写操作_file

这个是案例最终要实现的效果,在姓名和电话号码直接添加分割符号。

这里有一点需要主要的是,这个案例并不是直接在原先的txt文档上面进行修改的,而是新建一个新的txt文件重新写入新的内容。

好了废话不多说,看看这个案例具体是怎么具体实现的。

这个案例分为三个模块:1.文件读取模块,2.姓名电话分离模块,3.文件写入模块

1.文件读取模块:

/**
* 功能:Java读取txt文件的内容
* 步骤:1:先获得文件句柄
* 2:获得文件句柄当做是输入一个字节码流,需要对这个输入流进行读取
* 3:读取到输入流后,需要读取生成字节流
* 4:一行一行的输出。readline()。
* 备注:需要考虑的是异常情况
* @param filePath
*/
public static String readTxtFile(String filePath) {
StringBuilder content = new StringBuilder("");
try {
String encoding = "UTF-8";
File file = new File(filePath);
if (file.isFile() && file.exists()) {
InputStreamReader read = new InputStreamReader(new FileInputStream(file), encoding);
BufferedReader bufferedReader = new BufferedReader(read);
String lineTxt = null;
while ((lineTxt = bufferedReader.readLine()) != null) {
String[] result = getNamePhone(lineTxt);
System.out.println(lineTxt);
content.append(result[0] + "----" + result[1]);
content.append("\r\n");// txt换行
}
read.close();
} else {
System.out.println("找不到指定的文件");
}
} catch (Exception e) {
System.out.println("读取文件内容出错");
e.printStackTrace();
}
return content.toString();
}

2.姓名电话分离模块:

public static String[] getNamePhone(String str) {
String[] result = new String[2];
int index = 0;
for (int i = 0; i < str.length(); i++) {
if (str.charAt(i) >= '0' && str.charAt(i) <= '9') {
index = i;
break;
}
}
result[0] = str.substring(0, index);
result[1] = str.substring(index);
return result;
}

3.文件写入模块:

public static void printFile(String content) {
BufferedWriter bw = null;
try {
File file = new File("D:/filename.txt");
if (!file.exists()) {
file.createNewFile();
}
FileWriter fw = new FileWriter(file.getAbsoluteFile());
bw = new BufferedWriter(fw);
bw.write(content);
bw.close();
} catch (IOException e) {
e.printStackTrace();
}
}

通过这三个模块就可以实现对文件的读取操作了,然后对信息进行处理,最后将处理好的信息添加到新的文件中去。

这里需要注意的是:项目的编码格式要写成utf-8,否则会出现乱码的情况。

Java中对文件的读写操作_java_02

到这里文件的读写操作就完结了,是不是特别简单方便。