我正在尝试从第二个文件中读取名称,但只从每个文件中随机选取10个,在同一输出文件中总共20个。但无法弄清楚如何从第二个文件读取并放入相同的输出。
public class example2 {
public static void main(String[] args) throws IOException
{
// Read in the file into a list of strings
BufferedReader reader = new BufferedReader(new FileReader("textfile.txt"));
//BufferedWriter bw = new BufferedWriter(new FileWriter("out.txt"));
List<String> lines = new ArrayList<String>();
String line = reader.readLine();
while( line != null ) {
lines.add(line);
line = reader.readLine();
}
try (BufferedWriter writer = new BufferedWriter(new FileWriter("randomNames.txt"))) {
Random random = new Random();
Set<String> usedNames = new HashSet<String>(20);
while (usedNames.size() < 20) {
int rowNum = random.nextInt(lines.size());
String name = lines.get(rowNum);
if (!containsNameWithSameFirstCharacter(usedNames, name)) {
usedNames.add(name);
writer.write(name);
writer.newLine();
}
}
writer.flush();
}
}
private static boolean containsNameWithSameFirstCharacter(Collection<String> names, String name) {
for (String anotherName: names) {
if (anotherName.charAt(0) == name.charAt(0)) {
return true;
}
}
return false;
}
}
答案 0 :(得分:0)
在我看来,您最好将所有文件都读入两个列表,然后从每个文件中取出项目,直至获得输出列表。
类似的东西:
List<String> list1 = Files.readAllLines(path1);
List<String> list2 = Files.readAllLines(path2);
List<String> output = new ArrayList<>();
Collections.shuffle(list1);
Collections.shuffle(list2);
while (output.size() < 20) {
addFromList(list1, output);
addFromList(list2, output);
}
private void addFromList(List<String> from, List<String> to) {
String name = from.remove(0);
while (containsNameWithSameFirstCharacter(to, next))
name = from.remove(0);
to.add(name);
}
这需要对空列表进行一些错误检查,但希望你能得到这个想法。
答案 1 :(得分:0)
public static void main(String[] args){
try {
BufferedWriter writer = new BufferedWriter(new FileWriter(new File("outputfile.txt")));
List<String> a = readFile(new File("textfile1.txt"));
List<String> b = readFile(new File("textfile2.txt"));
List<String> all = a;
all.addAll(b);
Random random = new Random();
for(int i= 0; i < 10;){
int l = random.nextInt(all.size() - 1);
i++;
String n = all.get(l);
writer.newLine();
writer.write(n);
}
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
private static List<String> readFile(File file) throws IOException {
Path p = Paths.get(file.toURI());
List<String> ls = Files.readAllLines(p);
return ls;
}
这将读取这两个文件,获取其内容,将它们添加到列表中,选择其中的10个,然后将它们写入文件。一个名字=一行。
当然,这不是您的所有代码。这只是一个为您提供技巧的启动器。