简体   繁体   English

在 Mac 上创建 Java 中的文件

[英]Creating Files in Java on a Mac

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!我正在尝试创建一个简单的 txt 文件,但由于某种原因它无法正常工作 - 我是一个完整的初学者,从下面可以明显看出!

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.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我能够使用以下 Using FileWriter 和 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.此代码应在当前工作目录中创建一个名为“FoSho.txt”的空文件。

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.为了正确起见,您应该确保close() Formatter ,但我认为这不会成为创建文件的问题。

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.如果您从 IDE 启动它,您需要知道 IDE 正在选择什么。 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 .您没有向Formatter写入任何内容。 Call its format() method.调用它的format()方法。

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.如果找不到,请进行查找器搜索。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM