简体   繁体   中英

Scanner for JFileChooser?

My jave code can read the the text file completely, but how I can make it scan the text file and show it has some corrupted codes ??

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.Scanner;

import javax.swing.JFileChooser;


/**
 *
 * @author 
 */
public class NewMain {


public static void main(String[] args) throws IOException
{

   // Use file dialog to select file.
   JFileChooser chooser = new JFileChooser();
   int result = chooser.showOpenDialog(null);

   // This assumes user pressed Open
   // Get the file from the file 
   File file = chooser.getSelectedFile();
   // Open the file
   FileReader reader = new FileReader(file);

   // Use read, which returns an int
   int i = reader.read();
   while (i != -1)
   {
       // Convert to char and print
       char ch = (char)i;
       System.out.print(ch);
       // Get next  from read()
       i = reader.read();
   }
   // reader.close();


}
        }
    }

The Text file has:

0.2064213252847991ZONK6, 48, 32, 81 // corrupted code 

0.9179703041697693, 36, 58, 3, 68 

0.10964659705625479, 74, 89, 69, 39 

0.322267984407108, 27, 87, 89, 69 

0.228123305601ZONK5, 76, 48, 23, 78 // corrupted code 

Any code in the text file that has ZONK is the corrupted one

Read the javadoc: Scanner has a constructor taking a File as argument .

Constructs a new Scanner that produces values scanned from the specified file.

Better use BufferedReader which can read line by line like this.

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.Scanner;

import javax.swing.JFileChooser;

public class NewMain {
    public static void main(String[] args) throws IOException{
        // Use file dialog to select file.
        JFileChooser chooser = new JFileChooser();
        int result = chooser.showOpenDialog(null);
        // This assumes user pressed Open
        // Get the file from the file 
        File file = chooser.getSelectedFile();
        // Open the file
        java.io.BufferedReader reader = new java.io.BufferedReader(new java.io.FileReader(file));
        String line = reader.readLine();
        while (line != null){
            System.out.print(line);
            if (line.contains("ZONK")){
                System.out.println("    // corrupted code");
            }else{
                System.out.println("");
            }
            line = reader.readLine();
        }
        reader.close();
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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