下面我用一个案例做实验的具体教程,首先我从网上下载了一个四级单词词汇
里面的行数我用代码算了一下是4604行。
然后我用Java代码将它的所有单词取出来,没有名词解释,也没有汉译,只有单词
从上面的图片中,我们明显的可以看到每个单词后面有一个空格,之后才是解释,和汉译,所以只要一空格为分隔符,就可以完成分隔
再下面代码中需要注意的是widows的换行符是\r\n
package com.wordSearch.cc;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintWriter;
/**
*
* @author SunnyBoy
* @version Time:2017年7月29日 下午7:55:39
*/
public class WordFormat {
public static void main(String[] args) throws IOException {
String path = "D:\\test/levelFourWord.txt";
String path1 = "D:\\test/newFourWord.txt";
File file = new File(path);
File file1 = new File(path1);
BufferedReader br = new BufferedReader(new FileReader(file));
PrintWriter pw = new PrintWriter(file1);
String str = null;
while ((str = br.readLine()) != null) {
int n = 0;
n = str.indexOf(" ");
if (n > 0) {//if语句主要用来判断,该单词是否有空格为分隔符的
String s = str.substring(0, n);
pw.print(s+"\r\n");//这里主要是将一字符串打入一个文本中
}
else pw.print(str+"\r\n");
}
pw.close();这个主要是结束打印文本
}
}
运行之后生成的文本
为了实现部分的代码实现,这里我再补充一点,我最后又将这个文本做一个排序,因为有的项目需要进行对这个文本查找的时候,这个文本就需要排序了
package com.wordSearch.cc;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Arrays;
/**
*
* @author SunnyBoy
* @version Time:2017年7月29日 下午8:02:53
*/
public class WordSort {
public static void main(String[] args) throws IOException {
String path = "D:\\test/newFourWord.txt";
String path1 = "D:\\test/newFourWord1.txt";
File file = new File(path);
File file1 = new File(path1);
BufferedReader br = new BufferedReader(new FileReader(file));
PrintWriter pw = new PrintWriter(file1);
String str = null;
String[] string = new String[4604];//因为知道了具体的读入个数,我这里直接定义了具体的数组
int i = 0;
while ((str = br.readLine()) != null) {
string[i++] = str;
}
Arrays.sort(string);//直接使用jdk中封装的排序函数进行排序
for(int k = 1;k<i;k++) {
pw.print(string[k]+"\r\n");
}
pw.close();
}
}
排序后就成下面的样子了
这就是我自己琢磨出来的一些io代码,如果又哪些方面不对,还请告知,谢谢