简体   繁体   中英

How to execute some piece of code randomly

hi i am writing some data to a file if i have 10000 lines in 1000 line i want some content like "N/D" in the remaing i have get "D" but here the problem is not in sequence it has to get randomly "D" in 1000 lines.... File newfile = new File("/root/Documents/"+name+".txt");

// if file doesnt exists, then create it
if (!newfile.exists()) {
    newfile.createNewFile();
}
FileWriter fw = new FileWriter(newfile.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);



FileInputStream file = new FileInputStream(new File(filePath));
XSSFWorkbook workbook = new XSSFWorkbook(file);
XSSFSheet sheet = workbook.getSheetAt(0);
Iterator rows = sheet.rowIterator();
while (rows.hasNext()) {
    XSSFRow row = (XSSFRow) rows.next();
    Iterator cells = row.cellIterator();

    List dd = new ArrayList();
    while (cells.hasNext()) {
        XSSFCell cell = (XSSFCell) cells.next();

        String mobileNumber=data.formatCellValue(cell);

        String mobile=mobileNumber.substring(0, 5)+"****";
        String content=date +" "+ mobile +" " + encode + " "+"N/D";
        bw.write(content);
        bw.newLine();
    }
}
file.close();
 bw.close();

System.out.println("Done");

Create a counter: before you make your content String, initialize a Integer (eg int i = 0). Then you start a if clause: if(i<1000){ here you make your string with the Ds, then you add 1 to your integer} Here is how I'd code it like:

 while (cells.hasNext()) {
            XSSFCell cell = (XSSFCell) cells.next();

            String mobileNumber=data.formatCellValue(cell);
            String mobile=mobileNumber.substring(0, 5)+"****";
            String content=date +" "+ mobile +" " + encode + " ";
            int i = 0;
            if(i<=1000){
                content = content + "D";
            }
            else{
                content = content + "ND";
            }
            bw.write(content);
            bw.newLine();
        }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM