![](/img/trans.png)
[英]I need to count the number of times a substring occurs in a file using scanner and JFIleChooser
[英]Scanner for JFileChooser?
我的jave代碼可以完全讀取文本文件,但是如何使它掃描文本文件並顯示它具有一些損壞的代碼?
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的任何代碼均已損壞
閱讀javadoc:Scanner有一個構造函數,以File作為參數 。
構造一個新的Scanner,該掃描儀生成從指定文件掃描的值。
最好使用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();
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.