Java中的文件操作 [英] Files Operations in Java

查看:63
本文介绍了Java中的文件操作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请帮助我某人........一个从文本文件中随机显示10行的程序...我将非常感谢....:)

Please help me someone........a program which randomly displays 10 lines from a text file......i will be really really thankful.......:)

推荐答案

此处有两个选项:

1.将文件逐行读入字符串数组.生成介于0和数组长度之间的随机数-1.如果已经使用过,请确保生成一个新的数字.还要确保该文件至少有十行.使用随机数选择相应的数组条目.

2.对于太大而无法放入内存的文件,请分两次进行.首先逐行读取文件,但不存储行数.然后生成十个数字(如上),它们介于0和文件的行数之间.将这些随机数再次存储在数组中,以确保它们唯一.将该数组按升序排序.现在,逐行再次读取文件,当当前数组位置的随机数与文件的当前行号匹配时,输出当前行并前进到下一个数组位置.

干杯!

-MRB
Two options here:

1. Read file line by line into a string array. Generate random numbers between 0 and array length - 1. Make sure to generate a new number if it was already used. Also make sure that said file has at least ten lines. Use the random number to pick the corresponding array entry.

2. For files that would be too large to fit into memory do this in two passes. First read the file line by line counting the number of lines but not storing them. Then generate ten numbers like above that are between 0 and the line count of your file. Store these random numbers in an array again making sure to keep them unique. Sort that array in ascending order. Now read your file again line by line and when the random number at the current array position matches the current line number of the file output the current line and advance to next array position.

Cheers!

-MRB


这篇关于Java中的文件操作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆