Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert String to File in Java

Tags:

java

string

file

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?

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    } 
like image 626
tzg Avatar asked Jul 20 '12 16:07

tzg


People also ask

Can we convert String to file in Java?

Saving a String into files can be done in a few ways using Java. In this article, we'll show some common methods for writing a String into a file.

How do I convert a String to a file?

Perhaps the cleanest, most succinct solution to write a String to a File is through the use of the FileWriter. With this class, you pass its constructor the File object that you'd like to write to, and then you call its write method to write strings of data to the file.


1 Answers

File file = new File(userInput);

like image 195
jrad Avatar answered Sep 28 '22 10:09

jrad