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

时间:2023-02-08 21:47:46

I have code that asks the user to input a log file name so it knows what file it is to parse and sort.

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

To be able to parse correctly, the FileSource.parseXML reads a variable type of File. So, the input String needs to be converted to a File. How would this be done?

为了能够正确解析,FileSource.parseXML读取变量类型的File。因此,输入String需要转换为File。这怎么办?

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  

}

3 个解决方案

#1


27  

File file = new File(userInput);

文件文件=新文件(userInput);

#2


3  

From Oracle's javadoc (v7) http://docs.oracle.com/javase/7/docs/api/:

来自Oracle的javadoc(v7)http://docs.oracle.com/javase/7/docs/api/:

  File(String pathname) 
            Creates a new File instance by converting the given pathname string into an abstract pathname

#3


2  

Seeing that you have the file name, you should just be able to make a File:

看到你有文件名,你应该只能创建一个文件:

File file = new File(filename);

See this javadoc for more information about Files.

有关Files的更多信息,请参阅此javadoc。

#1


27  

File file = new File(userInput);

文件文件=新文件(userInput);

#2


3  

From Oracle's javadoc (v7) http://docs.oracle.com/javase/7/docs/api/:

来自Oracle的javadoc(v7)http://docs.oracle.com/javase/7/docs/api/:

  File(String pathname) 
            Creates a new File instance by converting the given pathname string into an abstract pathname

#3


2  

Seeing that you have the file name, you should just be able to make a File:

看到你有文件名,你应该只能创建一个文件:

File file = new File(filename);

See this javadoc for more information about Files.

有关Files的更多信息,请参阅此javadoc。