【发布时间】:2017-08-25 17:41:14
【问题描述】:
我是 Java 新手,目前正在学习如何读取文件、执行工作并将结果写入文件。我的代码可以无错误地运行,但我不知道为什么输出文件不能从控制台打印出任何内容(它必须打印每行的最后一个字)。谁能指出我如何修复以使其正常工作? 非常感谢。 这是我的代码。
import javax.swing.JButton;
import javax.swing.JFileChooser;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;
public class ReadingWriting {
private static BufferedReader reader;
private static BufferedWriter writer;
private static String currentLine;
private static String result;
public static void main(String[] arg) {
File inputFile=null;
JButton open= new JButton();
JFileChooser jfc = new JFileChooser();
jfc.setCurrentDirectory(new java.io.File("."));
jfc.setDialogTitle("ReadingWriting");
if (jfc.showOpenDialog(open) == JFileChooser.APPROVE_OPTION){
inputFile = jfc.getSelectedFile();
try {
reader = new BufferedReader(new FileReader(inputFile));
}catch (FileNotFoundException e){
System.out.println("The file was not found");
System.exit(0);
}
}
try {
Scanner input = new Scanner(inputFile);
while ((currentLine = reader.readLine()) != null){
currentLine = currentLine.trim();
String[] wordList = currentLine.split("\\s+");
String result =wordList[wordList.length-1];
System.out.println(result+"");
}
input.close();
reader.close();
}catch (IOException e2){
System.out.println("The file was not found");
System.exit(0);
}
try{
File outFile = new File("src/result.txt");
writer= new BufferedWriter(new FileWriter(outFile));
writer.write(result+"");
writer.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
输入文件(hello.txt):
你好世界
他是个好孩子
345 123 46 765
输出文件(result.txt):
世界
男孩
765
我目前的 result.txt 文件:
空
【问题讨论】:
-
您将
result隐藏为try块内的局部变量。 -
另外,您正在将最后一个
result写入文件。您需要为每行的最后一个单词创建一个列表或数组,然后将其写入输出文件。
标签: java file bufferedreader bufferedwriter