在 Java 中将字符串转换为文件

2022-09-01 16:51:05

我有代码要求用户输入日志文件名,以便它知道要解析和排序的文件。

为了能够正确解析,读取变量类型为 。因此,需要将输入转换为 .如何做到这一点?FileSource.parseXMLFileStringFile

import java.io.*;
import java.util.*;

public class Main
{
    public static void main( String[] args )
    {
        FileSource src;
        File fd=null;
        int rc = 0;
        int count = 0;
        Record rec;

      //ask user what file to parse
      Scanner input = new Scanner(System.in);
      System.out.println("Enter file name:");
      String filename = input.nextLine();

      //TODO turn filename into fd


        //parse the records
        src = FileSource.parseXML( fd );


        //print out the number of records parsed
        rc = src.getRecordCount();
        System.out.println(rc);


        //print out all records. 
        for( int i = 0; i < rc; i++)
        {
            rec = src.getRecord( i );
            System.out.println( rec.toString());
        } //end for loop

        return;
    }//end main method  

}

答案 1

File file = new File(userInput);


答案 2

看到你有文件名,你应该能够制作一个文件:

File file = new File(filename);

有关文件的更多信息,请参阅此 javadoc