我正在尝试用Java编写一个函数,它从txt文件返回下一个升序序列(run),让我们说函数的返回类型是 ArrayList的
我的示例文件 input.txt 包含下一个值:78123421。因此,就运行而言,该文件有4次运行:| 78 | 1234 | 2 | 1 |。
我想在这里尝试的是,当我从main()调用此函数四次时,应该打印类似
的内容1.run: 78,
2.run: 1234,
3.run: 2,
4.run: 1
或只打印两个电话
1.run: 78,
2.run: 1234
我尝试使用BufferedReader / FileReader和RandomAccessFile来解决我的问题,但到目前为止还没有可行的解决方案,请帮助:/
所以这就是我到目前为止所拥有的。主要思想是使用RandomAccessFile并在输入中读取,只要满足运行条件即可。但读者更多地读取一个值,这就是为什么我在下一个函数调用发生时使用seek()开始在正确位置读取的原因。代码中必定存在错误,因为它不会打印所有运行或仅触发Exception。
import java.io.File;
import java.util.ArrayList;
import java.io.RandomAccessFile;
public class GetRunsFromFile
{
static long start = 0;
static long read_len = 0;
public static void main(String[] args) throws Exception
{
File in = new File("C:/Users/henrich/Desktop/Gimp.txt");
RandomAccessFile raf = new RandomAccessFile(in,"r");
ArrayList<Integer> current_run = new ArrayList<Integer>();
for(int i=1;i<=4;i++)
{
current_run = getNextRun(raf);
printArrayList(current_run);
}
raf.close();
}
private static ArrayList<Integer> getNextRun(RandomAccessFile raf) throws Exception
{
int v;
String line;
int val = Integer.MIN_VALUE;
ArrayList<Integer> run = new ArrayList<Integer>();
while((line=raf.readLine())!= null)
{
v = Integer.parseInt(line.trim());
if(v >= val)
{
read_len = raf.getFilePointer() - start;
start = raf.getFilePointer();
run.add(v);
val = v;
}
else
{
raf.seek(raf.getFilePointer() - read_len);
start = raf.getFilePointer();
return run;
}
}
return null;
}
private static void printArrayList(ArrayList<Integer> al)
{
for(int i=0; i<al.size(); i++)
{
System.out.print(al.get(i) + " ");
}
System.out.println();
System.out.println("------");
}
}
如有其他问题,请告知我们。
注意:它应该只适用于升序运行和任何长度的文件。
感谢您的支持。
答案 0 :(得分:0)
有几种方法可以做到这一点。
例如,使用int调用函数并使其返回一个int,引用最后打印的char的编号。
运行Exaple:
第一次运行返回2后导致打印文本的长度为2 在第二次运行返回6之后,打印文本的长度是从上一次循环开始的4 + 2 ......等等。
public int function(int startPoint){
// do stuff here
return lastIndexofPrintChar;
}
然后像这样调用你的函数
loop{
int result=0;
result= function(x);
}
您还可以对文件进行出版,并删除您打印的每个字符串。
答案 1 :(得分:0)
private static void getNextRun()
{
try
{
BufferedReader br = new BufferedReader(new FileReader(new File("C:/Users/henrich/Desktop/Gimp.txt")));
br.skip(skip_lines);
int v;
String line;
int val = Integer.MIN_VALUE;
ArrayList<Integer> al = new ArrayList<Integer>();
while((line=br.readLine())!= null)
{
skip_lines += line.length()+2;
v = Integer.parseInt(line.trim());
if(v >= val)
{
al.add(v);
val = v;
}
else
{
skip_lines -= line.length() + 2;
printArrayList(al);
break;
}
}
br.close();
}
catch (Exception e){System.out.println("EOF");}
}