簡體   English   中英

Java - 文件讀取和分隔符需要幫助

[英]Java - Help needed with file reading and delimiter

我有一個包含內容的文件:

  • 85,70,95,82,75
  • 70,78,85,62,47,53,32
  • 99,88,75,85,69,72
  • 79,84,86,91,84,89,78,82,70,75,82
  • 56,68,0,56
  • 96,82,91,90,88

我需要使用 java 掃描儀 class 編寫代碼來讀取和 output 代碼按以下順序:

  • 85,70,95,82,75
  • 85 70 95 82 75
  • 70,78,85,62,47,53,32
  • 70 78 85 62 47 53 32
  • 99,88,75,85,69,72
  • 99 88 75 85 69 72 等...

但是,我似乎無法讓我的代碼為我的一生工作,我無法弄清楚我不理解什么。 我已經非常接近我的結果,但我已經嘗試了很多解決方案,我只是放棄了。 這是我擁有的當前代碼。 這幾乎是我得到的最好結果。

import java.io.*;
import java.util.*;
public class FileIO
{
    public static void main(String[] args) throws IOException 
    {
        File fileObj2 = new File("Scores.txt");
        Scanner scan2 = new Scanner(fileObj2);
        String line = "";
        String x = "";      

        Scanner scan3 = null;
        scan3 = new Scanner(fileObj2);  
        scan3.useDelimiter(",");

        System.out.println();
        System.out.println("Second Files data below \n ------------- 
        ---------");
        while (scan2.hasNextLine()){
            line = scan2.nextLine();
            System.out.println(line);
            while (scan3.hasNext()){
                line2 = scan3.next();
                System.out.print(line2 + " " );
            }
        }
    }
}

這給了我 output

85,70,95,82,75
85 70 95 82 75
70 78 85 62 47 53 32
99 88 75 85 69 72
79 84 86 91 84 89 78 82 70 75 82
56 68 0 56
96 82 91 90 88 70,78,85,62,47,53,32
99,88,75,85,69,72
79,84,86,91,84,89,78,82,70,75,82
56,68,0,56
96,82,91,90,88

您可以使用replace方法來獲得所需的結果。 請參閱下面的代碼段供您參考。

String line = "87,88,89,90,91";
System.out.println(line);
System.out.println(line.replace(',',' '));

代碼中的小改動,請在下面找到它們,

            while (scan2.hasNextLine()){
            line = scan2.nextLine();
            System.out.println(line);
            scan3 = new Scanner(line);
            scan3.useDelimiter(","); 
            while (scan3.hasNext()){
                System.out.print(scan3.next());
            }
        }

您可以使用replaceAll方法刪除逗號。

分數.txt:

85,70,95,82,75
70,78,85,62,47,53,32
99,88,75,85,69,72
79,84,86,91,84,89,78,82,70,75,82
56,68,0,56
96,82,91,90,88

代碼:

Scanner in = new Scanner(new File("Scores.txt"));
while(in.hasNextLine()) {
        String line = in.nextLine();
        String out = line.replaceAll(","," ");
        System.out.println(line);
        System.out.println(out);
}

Output:

70,78,85,62,47,53,32
70 78 85 62 47 53 32
99,88,75,85,69,72
99 88 75 85 69 72
79,84,86,91,84,89,78,82,70,75,82
79 84 86 91 84 89 78 82 70 75 82
56,68,0,56
56 68 0 56
96,82,91,90,88
96 82 91 90 88

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM