开发者

Creating Files in Java on a Mac

开发者 https://www.devze.com 2023-03-22 02:36 出处:网络
I\'m trying to create a simple txt file but its not working for some reason - I\'m a complete beginner as will be evident from below!

I'm trying to create a simple txt file but its not working for some reason - I'm a complete beginner as will be evident from below!

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

import javax.swing.JFrame;

public class Stuff{

    public static void main (String[] args) {

        final Formatter x;
        try {
            x = new Formatter("FoSho.开发者_JAVA百科txt");
            System.out.println("You created a file called FoSho.txt");
        } catch (Exception e) {
            System.out.println("You got an error");
        }
    }
}   


I was able to create a text file with the following Using FileWriter and BufferedWriter

public static void main(String[] args) {
        // TODO code application logic here
        String filename = "<//Enter the location you want the file//>";
        FileWriter fstream;

        try {
            fstream = new FileWriter(filename);
            BufferedWriter out = new BufferedWriter(fstream);
            out.write("My Name is Bobby Bob");
            out.newLine();                                  
            out.flush();
            out.close();
        } catch (IOException e) {
            e.printStackTrace();          
      }

    }


This code should create an empty file called "FoSho.txt" in the current working directory.

For correctness, you should make sure that you close() the Formatter, but I don't think that will be a problem in creating the file.

Possibilities for "not working" include:

  1. You don't know what "the current working directory" is. If you launch this from an IDE, you need to know what the IDE is choosing. Running it yourself, from the command line, it should be clear.

  2. It's raising an exception. If you get any error messages, include them in your post.


You're not writing anything to the Formatter. Call its format() method.


When I run this code on my system, the file creates successfully, which editor are you using?

The file should be somewhere on your system. If you can't find it, do a finder search.

0

精彩评论

暂无评论...
验证码 换一张
取 消