一个words数组,数组中每个字符串的格式为“词性:单词”
- String[] words = {“verb:eat”,“verb:drink”,“verb:sleep”,“verb:play”,“noun:rice”,
“noun:meat”,“noun:hand”,“noun:hair”};
根据单词性质动词verb全部存入verb.txt文件中
根据单词性质名词noun全部存入noun.txt文件中
import java.io.FileOutputStream;
import java.io.IOException;
public class Work2 {
public static void main(String[] args) throws IOException {
String[] words = {"verb:eat", "verb:drink", "verb:sleep", "verb:play",
"noun:rice", "noun:meat", "noun:hand", "noun:hair"};
//用String类里的contains判断当前字符串包含noun还是verb
//把同词性的单词拼接到一个字符串中
String verbs = "", nouns = "";//最终字符串
String v = "verb", n = "noun";//参照字符串
for (int i = 0; i < words.length; i++) {
if (words[i].contains(v)) {
verbs += words[i];
verbs += "\n";//为了复制到文件能自动换行
}
if (words[i].contains(n)) {
nouns += words[i];
nouns += "\n";
}
}
//jvm把数据写到外存
FileOutputStream out = new FileOutputStream("verb.txt");
out.write(verbs.getBytes());
out = new FileOutputStream("noun.txt");
out.write(nouns.getBytes());
//资源释放
out.close();
}
}