【发布时间】:2018-03-15 22:19:34
【问题描述】:
我真的是编程新手,我有基本的知识。
我正在尝试制作一个程序:
- 读取已有文件的路径
- 读取我想从现有文件中提取的字符串。
- 读取创建新文件的路径。
- 使用从点 3 开始的指定路径创建一个文件。其中包含从点 2 选择的单词。
例如,如果我有一个 log/txt 文件。从中我想提取我在第 2 点从键盘读取的所有字符串。
在此之后,我希望将所有这些字符串写入一个新的 log/txt 文件中。
我希望你明白我想要做什么。
这是我到现在为止写的,但我有点卡在想法上,因为我还在学习编码语法,所以很难实现它。
package com.kwextractor;
import java.io.*;
import java.util.Scanner;
public class Main {
public static String inputFilePath;
public static String outputFilePath;
public static String textToGet;
public static void main(String[] args) throws IOException {
Scanner filePathIn = new Scanner(System.in);
Scanner inputText = new Scanner(System.in);
Scanner filePathOut = new Scanner(System.in);
System.out.println("Enter file path:");
inputFilePath = filePathIn.nextLine();
System.out.println("Enter the string you want to extract:");
textToGet = inputText.nextLine();
System.out.println("Enter the path of the exported file:");
outputFilePath = filePathOut.nextLine();
File inputFile = new File(inputFilePath +".txt");
BufferedReader inputReader = new BufferedReader(new FileReader(inputFile));
String nextLine;
while ((nextLine = inputReader.readLine()) != null)
{
if (nextLine.equals(textToGet)) {
BufferedWriter writer = null;
try {
File outputFile = new File(outputFilePath+".txt");
System.out.println(outputFile.getCanonicalPath());
writer = new BufferedWriter(new FileWriter(outputFile));
writer.write(textToGet);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
// Close the writer regardless of what happens...
writer.close();
} catch (Exception e) {
}
}
}
}
}
}
【问题讨论】:
-
如果您一直受困于想法,那么您想要做的最后件事就是向我们提出一个不完整的问题。花点时间回到白板上,具体规划出你想用你的程序完成什么。然后朝着完成的方向努力。当您在某个特定部分陷入困境时,请回来询问我们。到时候你会更好的装备它。
-
出于教育目的,这段代码已经是一项艰巨的工作......尝试 - 真正 - 理解代码,例如异常处理本身已经很重要了,因为那里有很多代码没有足够的异常处理......大多数时候它看起来像 `catch (Exception e) { e.printStackTrace(); }` 甚至更好的
//TODO,还有流、缓冲区,甚至没有理由将变量公开,也没有理由在您的代码中将其设为静态。 (我希望这些是你学习编程的足够“想法”) -
@makoto 我在这里没有看到任何不完整的问题。我准确地解释了我想要创建的内容,并添加了代码,希望有人会尝试解释我做错了什么,因为当然程序没有运行,也许有人可以纠正我。
-
是的,您希望我们解释如何创建整个应用程序这一事实使您的问题“不完整”充其量。你不能只指望我们在这里这样做。我们可以在零件方面为您提供帮助,但您必须付出努力。我强烈建议您按照我上面的建议进行练习。
-
@moneydhaze 我会得到所有这些提示并尝试应用它们。谢谢
标签: java file filewriter file-read