I need to create a file in java. However there's errors in my output. Could you please help me out?
import java.io.*;
/**
* Write a description of class CreateFile1 here.
*
* @author (your name)
* @version (a version number or a date)
*/
public class CreateFile1
{
public static void main(String[] args)throws IOException
{
File f;
f=new File("C:\MyFile.txt");
if(!f.exists()){
f.createNewFile();
System.out.println("New file"+ "C:\MyFile.txt"+" has been created to the current directory");
}
}
}
1
Expert's answer
2010-09-30T12:34:45-0400
Try to use this code , this will help you 01.import java.io.BufferedWriter; 02.import java.io.FileWriter; 03.import java.io.File; 04.import java.io.Writer; 05.import java.io.FileNotFoundException; 06.import java.io.IOException; 07. 08.public class WriteTextFileExample 09.{ 10. public static void main(String[] args) 11. { 12. Writer writer = null; 13. 14. try 15. { 16. String text = "This is a text file"; 17. 18. File file = new File("write.txt"); 19. writer = new BufferedWriter(new FileWriter(file)); 20. writer.write(text); 21. } catch (FileNotFoundException e) 22. { 23. e.printStackTrace(); 24. } catch (IOException e) 25. { 26. e.printStackTrace(); 27. } finally 28. { 29. try 30. { 31. if (writer != null) 32. { 33. writer.close(); 34. } 35. } catch (IOException e) 36. { 37. e.printStackTrace(); 38. } 39. } 40. } 41.}
Comments
Leave a comment