2011-07-22 46 views
2

我正在嘗試創建一個簡單的txt文件,但由於某種原因它不工作 - 我是一個完整的初學者,從下面可以看出!在Mac上用Java創建文件

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"); 
     } 
    } 
} 
+0

的[寫入文件中的Java]可能重複(http://stackoverflow.com/questions/5239424/寫入到一個文件在Java) – 2011-07-22 17:38:44

+2

你可以詳細說明「它不工作」? –

+0

當我尋找一個名爲FoSho.txt的文件時,我找不到一個, – Ravin

回答

3

我能夠創建一個文本文件與以下 使用的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();   
     } 

    } 
0

此代碼應該在當前工作目錄中創建一個名爲「FoSho.txt」的空文件。

爲了正確,您應該確保您的close()Formatter,但我不認爲這將是創建文件的問題。

的可能性「不工作」包括:

  1. 你不知道什麼是「當前工作目錄」是。如果你從IDE啓動它,你需要知道IDE選擇什麼。從命令行自己運行它應該很清楚。

  2. 這引發了一個例外。如果您收到任何錯誤消息,請將其添加到您的帖子中。

0

你沒有寫任何東西給Formatter。調用其方法format()

0

當我在我的系統上運行此代碼時,該文件創建成功,您正在使用哪個編輯器?

該文件應該位於系統上的某個位置。如果找不到它,請執行查找器搜索。

+0

我認爲這可能只是我的垃圾箱中的一個文件,可以阻止它嗎? – Ravin