如果我运行程序两次,为什么不要制作两个文件?

时间:2015-09-02 01:26:12

标签: java file

我有一个制作文件的程序。我假设如果我运行该程序两次,我会得到两个相同的文件?或者一个文件会覆盖另一个?我做了一些代码,说明文件是否已经存在(如果我已经运行了一次程序),而不是显示一个窗口。但是,出于某种原因,代码总是成功地制作新文件?

package Files;

import java.awt.Font;
import java.io.File; //The file class gives info about files, ex: length, existence, etc. (filename.exists();)
import java.util.*;
import javax.swing.*;

public class Myfirstfileclass {

    public static void main(String[] args) {

        File myfile = new File("C:\\creationfiles\\jfklda.txt"); //Always use two backslashes, because one backslash escapes a swing, it interprets two as one though.

        if (! myfile.exists()) {
            newwindowsinceexists object = new newwindowsinceexists();




            final Formatter myformatter;

            try{ //Saying try this, if it gets an error then go over to catch.
                myformatter = new Formatter("Imadethisfileforyou.txt");
                System.out.println("It should have worked!");

                // This is the same as just making it all in one line, and writing:
                //final Formatter myformatter = new Formatter("Imadethisfileforyou.txt");
            }

            catch(Exception e){ //Execption is a fancy word for error
                Error error = new Error(); //Opens window saying you got an error
            }



        }

        if (myfile.exists()){
            alreadyexists existenceobj = new alreadyexists();
        }
    }
}
class alreadyexists extends JFrame{
    public alreadyexists(){
        super ("Did you run this program more than once?");

        JLabel didyou = new JLabel("Did you run this program more than once?");

        add(didyou);
        setVisible(true);
        setSize(getMaximumSize());
        setDefaultCloseOperation(DISPOSE_ON_CLOSE);

    }
}
class newwindowsinceexists extends JFrame {

    public newwindowsinceexists() {

        super("I will create a new file for you!");

        JLabel text = new JLabel("I will create you a new file");
        text.setFont(new Font("Courier New", Font.ITALIC, 30));

        add(text);

        setSize(getMaximumSize());
        setDefaultCloseOperation(DISPOSE_ON_CLOSE);
        setVisible(true);

    }

}
class Error extends JFrame{

    public Error(){

        super("Sorry, there's an error!");

        JLabel labelerror = new JLabel("There is an error, I am sorry");
        labelerror.setFont(new Font("Courier New", Font.ITALIC, 30));
        add(labelerror);

        setSize(250, 250);
        setDefaultCloseOperation(DISPOSE_ON_CLOSE);
        setVisible(true);
    }
}

它是否覆盖已创建的文件,如何在已经创建的情况下运行类alreadyexists,如何停止它?感谢您抽出时间阅读本文,我非常感谢您为帮助其他程序员所付出的努力。

0 个答案:

没有答案