繁体   English   中英

在Java中将输入文件解析为两个单独的文件

[英]Parse an input file into two separate files in java

我有一个如下所示的输入文件(例如):

10 12
1
2
...
9
10
1
2
...
11
12

第一个告诉接下来的10行是针对part1

接下来的12条线将用于part2

我想创建两个单独的文件part1.txtpart2.txt解析原始的input.txt文件。

那怎么办 有什么建议吗? 我正在使用Java扫描仪。

解决方案(部分):根据以下建议对我有用

    Scanner scanner = new Scanner(filename);        
    try {
        String[] first_line = scanner.nextLine().split("\\s+", 3); // reading the first line of the input file

        int EdgeCount = Integer.parseInt(first_line[0]);    
        int VertexCount = Integer.parseInt(first_line[1]);  
        String hasWeight = first_line[2];

        while (scanner.hasNextLine()) {
            if(EdgeCount != 0) { // check whether any more edges are left to read from input file
                Scanner edge_scanner = new Scanner(scanner.nextLine());

....

由于这听起来像是功课,所以我不会过多介绍代码细节,但是您可以阅读第一行,然后使用String类中的.split("\\\\s+")方法。

完成此操作后,您将得到一个数组,第一个位置为10 ,第二个位置为12

遍历下几行时,只需保留一个计数器并检查计数器的值是否小于或等于10。如果成立,则您知道需要输出一个文件。 如果条件不再成立,并且计数器现在大于10但小于或等于10 + 12 ,那么您知道应该在第二个文件中打印。

首先,逐行读取文件,将前10行写入part1.txt,然后在12行之后写入part2.txt。

为此使用这种模式:

BufferedReader br = new BufferedReader(new FileReader(“您的输入文件路径”));

    String line = null;

    int lineCounter = 1;

    while( (line = br.readLine()) != null)
    {
    if( (lineCounter % 23 ) < 11 )
    {
       //Write part1.txt
    }
    else if( (lineCounter %23) > 10 )
    {
        //write part2.txt
    }
    lineCounter++;
    }

    br.close();

尝试这个,

Scanner scanner = new Scanner(System.in);
br  = new BufferedReader(new FileReader("fileName.txt"));
int first = scanner.nextInt(); //10
int second = scanner.nextInt();//12
int x = 0;
int j = 0;
while ((sCurrentLine  = br.readLine()) != null) 
   {
     if (x <= first)
     {
        x++;
        //write in 1st file
     }
     else if (j <= second)
     {
        j++;
        //write in 2nd file
     }
}
br.close();

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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