有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

读写txt/日志文件的java程序

我对编程非常陌生,而且我有基本的知识

我正在尝试制作一个程序:

  1. 读取已存在文件的路径
  2. 读取要从现有文件中提取的字符串
  3. 读取创建新文件的路径
  4. 从第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) {
                    }
                }
            }
        }
    }
}

共 (0) 个答案