2013-12-10 2 views
0

Мой код jave может полностью прочитать текстовый файл, но как я могу заставить его сканировать текстовый файл и показать, что он имеет некоторые поврежденные коды?Сканер для JFileChooser?

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(); 


} 
     } 
    } 

Файл Текст имеет:

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 

Любой код в текстовый файл, который имеет Zonk является поврежден один

ответ

0

Лучше использовать BufferedReader, который может читать по строкам следующим образом.

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(); 
    } 
} 
0

Прочитайте документацию: Сканер имеет a constructor taking a File as argument.

Создает новый сканер, который производит значения, отсканированные из указанного файла.

Смежные вопросы