我的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的任何代码都是损坏的
答案 0 :(得分:0)
阅读javadoc:扫描仪已a constructor taking a File as argument。
构造一个新的Scanner,它生成从指定文件扫描的值。
答案 1 :(得分: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();
}
}