文件输出有问题

时间:2016-02-10 18:31:02

标签: java fileoutputstream

我希望能够从文件中读取20个随机名称并将它们放入新文件中。我该怎么做?

public class Assignment2 {

    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();
        }

        // Choose a random one from the list
        Random r = new Random();

        for (int i = 0; i < 20; i++) 
        {
           int rowNum = r.nextInt(lines.size ());
           System.out.println(lines.get(rowNum));
        }

    }
}

1 个答案:

答案 0 :(得分:0)

<div ng-controller='TimeCtrl as timeCtrl'>
    <p>Date: {{ timeCtrl.clock.time | date:'medium'}}</p>
     <p>Timer: {{ timeCtrl.timer.time | date:'mm:ss:sss'}}</p>
     <button type="button" ng-click="timeCtrl.timerStart()">Start</button>
     <button type="button" ng-click="timeCtrl.timerReset()">Reset</button>
     <button type="button" ng-click="timeCtrl.timerStop()">Stop</button>
</div>

如果您需要检查是否已使用某个号码,请将其添加到一个集合中:

try (BufferedWriter writer = new BufferedWriter(new FileWriter("randomNames.txt"))) {

    Random random = new Random();

    for (int i = 0; i < 20; i++) {
       int rowNum = random.nextInt(lines.size());
       writer.write(lines.get(rowNum));
       writer.newLine();
    }
}

检查是否存在具有相同第一个字符的其他名称:

try (BufferedWriter writer = new BufferedWriter(new FileWriter("randomNames.txt"))) {
    Set<Integer> usedNumbers = new HashSet<Integer>(20);
    Random random = new Random();
    int addedCount = 0;

    while (addedCount < 20) {
        int rowNum = random.nextInt(lines.size());
        if (usedNumbers.add(rowNum)) {
            writer.write(lines.get(rowNum));
            writer.newLine();
            addedCount++;
        }
    }
}

然后你做:

private static void containsNameWithSameFirstCharacter(Collection<String> names, String name) {
    for (String anotherName : names) {
        if (anotherName.charAt(0) == name.charAt(0)) {
            return true;
        }
    }
    return false;
}