Answer to Question #708 in Java | JSP | JSF for Gayethiri

Question #708
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"); } } }
Expert's answer
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.}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be first!

Leave a comment

Ask Your question

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS
paypal