Coldfusion 获取txt文件中的随机行。冷饮
如何在屏幕上显示文件中的随机行? 此txt文件包含第10k行。Coldfusion 获取txt文件中的随机行。冷饮,coldfusion,cfml,Coldfusion,Cfml,如何在屏幕上显示文件中的随机行? 此txt文件包含第10k行。 谢谢您可以这样做: <cffile action="read" file="#ExpandPath( './text.txt' )#" variable="pag"> pag=FileOpen(ExpandPath('./text.txt'),“read”); 计数器=0; 随机线=随机范围(1,10000); 而(不是FileisEOF(myfile)){ 计数器++; 如果(计数器==随机线){ x=FileR
谢谢您可以这样做:
<cffile action="read" file="#ExpandPath( './text.txt' )#" variable="pag">
pag=FileOpen(ExpandPath('./text.txt'),“read”);
计数器=0;
随机线=随机范围(1,10000);
而(不是FileisEOF(myfile)){
计数器++;
如果(计数器==随机线){
x=FileReadLine(pag);//读取行
写输出(“#x#”);
打破
}
}
文件关闭(pag);
这样做效率不高,而且还依赖于您知道文件中的行数。如果需要多次读取,那么最好只读取一次文件,并将每一行存储在数据库或持久存储范围中。然后你就可以很容易地从中获取任何记录。例如:
<cfscript>
pag = FileOpen(ExpandPath( './text.txt' ), "read");
counter = 0;
randomLine = randRange(1, 10000);
while(NOT FileisEOF(myfile)) {
counter++;
if (counter==randomLine) {
x = FileReadLine(pag); // read line
WriteOutput("#x#");
break;
}
}
FileClose(pag);
</cfscript>
//读取文件一次
pag=FileOpen(ExpandPath('./text.txt'),“read”);
行=[];
而(不是FileisEOF(myfile)){
arrayAppend(行,FileReadLine(pag));//读取行
}
文件关闭(pag);
//将'lines'存储在持久作用域或db等中
//这里我将应用程序范围用作一个简单的示例
application.filelines=行;
然后,您可以随机获取一行,而无需重新读取文件
<cfscript>
// read the file once
pag = FileOpen(ExpandPath( './text.txt' ), "read");
lines = [];
while(NOT FileisEOF(myfile)) {
arrayAppend(lines, FileReadLine(pag)); // read line
}
FileClose(pag);
// store the `lines` in a persistent scope or db etc
// here I'm using application scope as a simple example
application.filelines = lines;
</cfscript>
totalines=arrayLen(application.filelines);
随机线=随机范围(1,共行);
writeOutput(application.filelines[randomLine]);
将文件视为以chr(10)分隔的列表。使用listToArray
将其转换为数组。使用arrayLen
获取行数,使用randRange
获取随机数。然后输出该行。一个chr(10)分隔的列表,该列表可能会产生额外的字符。行分隔符因o/s而异。
<cfscript>
totalLines = arrayLen(application.filelines);
randomLine = randRange(1, totalLines);
writeOutput(application.filelines[randomLine]);
</cfscript>