2013-12-10 250 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 

在文本文件中的任何代碼,具有使...非常吃驚的是損壞的一個

回答

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