在通知读者文件名应以后缀.txt结尾后,如何将文件名作为字符串变量读取?

时间:2014-01-23 18:54:19

标签: java

您好我昨天发布了一个类似的问题,但现在我需要帮助将文件名作为字符串变量读取。附件是我更新的代码

import java.io.*;
import java.util.*;
public class SongWriter {

    public static void main(String[] args) {
        PrintWriter outputStream = null;

        // Scope must be outside the try/catch structure.
        String fileName1;
        Scanner keyboard = new Scanner(System.in);
        System.out.print("Enter the name of the file. The file should end in the suffix.txt ");
        fileName1 = keyboard.next();

        try {
            outputStream = new PrintWriter("Song.txt");
            // new FileOutputStream("Song.txt")
        } catch (FileNotFoundException e) {
            System.out.println("Error opening the file Song.txt.");
            System.exit(0);
        }

        System.out.println("\n classical songs has many lines");
        System.out.println("\nNow enter the three lines of your Song.");
        String line = null;
        //Scanner keyboard = new Scanner(System.in);
        int count;

        for (count = 1; count <= 3; count++) {
            System.out.println("\nEnter line " + count + ": ");
            line = keyboard.nextLine();
            outputStream.println(count + "\t" + line);
        }

        outputStream.close();
        System.out.println("\nYour Song has been written to the file song.txt.\n");
    } // end of main
} // end of class

我最初的问题是如何调整程序,以便首先询问要写入的文件的名称。使用Scanner类及其next()方法。在通知读者文件名应以后缀.txt结尾后,将文件名作为字符串变量读入 例如: - 歌曲的文件名为Song1.txt,Song2.txt和Song3.txt。 在其他人的帮助下,我能够在我的代码中使用scanner类和next()。有人可以告诉我为什么我的代码不起作用?

1 个答案:

答案 0 :(得分:1)

更改此行

// Use "Song.txt"
outputStream = new PrintWriter("Song.txt");

// Use the value stored in the fileName1 String.
outputStream = new PrintWriter(fileName1);

此外,你没有得到keyboard.next()整行,你应该这样做

fileName1 = keyboard.nextLine().trim();