如何用java读一个txt文件, 该txt文件每一行有一个英文名如John、Tom等,我想使用这些英文名随机的排列组合形成一个first name + middle name + last name的新的姓名列表保存到一新的txt文件里,请问如何实现。初学者求教,谢谢。
先用File实例化文件File file = new File(文件地址);再用BufferReader br = new BufferReader(file);读文件;然后bf.readLine()这个方法可以一行一行读,你用while循环可以全读出来。
之后读出来的内容你该知道怎么处理了撒。最后在实例化一个file_new,用BufferWriter把编辑好的东西写进去。
那你要判断哪些是可以作为姓的,哪些是可以作为名的。不能瞎组合。这得手工先把它们分开。
public static void main(String[] args)
{
List list = read();
write(list);
}
private static void write(List<String> list)
{
File file_write = new File("d:///name.txt");
BufferedWriter bw;
try
{
bw = new BufferedWriter(new FileWriter(file_write, true));
Random ra = new Random();
for (int i = 0; i < 23; i++)
{
int x = ra.nextInt(list.size());
int y = ra.nextInt(list.size());
int z = ra.nextInt(list.size());
bw.write(list.get(x) + " " + list.get(y) + " " + list.get(z));
bw.newLine();
}
bw.close();
}
catch (IOException e)
{
System.out.println("file not found!");
e.printStackTrace();
}
}
private static List<String> read()
{
String path = "d:///test.txt";
File file = new File(path);
ArrayList<String> list = null;
try
{
BufferedReader br = new BufferedReader(new FileReader(file));
String conent = "";
list = new ArrayList<String>();
while ((conent = br.readLine()) != null)
{
list.add(conent);
}
br.close();
}
catch (FileNotFoundException e)
{
System.out.println("file not found!");
e.printStackTrace();
}
catch (IOException e)
{
System.out.println("file read error!");
e.printStackTrace();
}
return list;
}
就是把它们全都保存在一个ArrayList里面就好了,然后用random函数随机出来仨数依次get就好了
具体多复杂啊?
还是读出来重新组合就行