如何在java中保存和打开文件(在cmd中)

Posted

技术标签:

【中文标题】如何在java中保存和打开文件(在cmd中)【英文标题】:How to save & open file in java ( in cmd) 【发布时间】:2015-03-18 16:12:14 【问题描述】:

我对编程完全陌生,这是我的第一个项目。到目前为止,我已经创建了 3 个类。我的主类允许用户输入数字(来自 kbentry 类),这些数字将被计算(使用 Calculating 类中的方法)以获得结果。现在我只需要将结果保存到一个目录,然后以后可以打开它。我在cmd中运行它。任何帮助表示赞赏。

//计算类

public class CalculatingRocketFlightProfile  //Calculation class

//Declaring variables
public double totalImpulse ;
public double averageImpulse;
public double timeEjectionChargeFires;
public double massEmptyVehicle;
public double engineMass;
public double fuelMass; 
//Declaring variables for outputs
public double theAverageMassOfTheVehicle; //declare variables to store  results of calculations
public double theVehiclesMaximumVelocity;

//Declaring variables of outputs
public double Gravity = 9.81; //Constant variable (default)

//Constructor
public CalculatingRocketFlightProfile(double totalImpulse, double   averageImpulse, double timeEjectionChargeFires, double massEmptyVehicle,
                                  double engineMass, double fuelMass)  //Setting the parameters 

this.totalImpulse  = totalImpulse;
this.averageImpulse = averageImpulse;
this.timeEjectionChargeFires = timeEjectionChargeFires;
this.massEmptyVehicle = massEmptyVehicle;
this.engineMass = engineMass;
this.fuelMass = fuelMass;


//Mutators and Accessors

//Accessors
//Methods for calculations - Calculating outputs, using inputs. 

public double theAverageMassOfTheVehicle() 
    return massEmptyVehicle + ((engineMass + (engineMass - fuelMass) )  / 2 ); //Formula to calculate Average mass 
//method

public double theVehiclesMaximumVelocity()  //Formula to calculate Maximum velocity
    return totalImpulse / theAverageMassOfTheVehicle();
//method

//主类

        public class Main  //Master class


        public static void main( String args[] ) //Standard header for main  method
        


        kbentry input = new kbentry(); //Creates object of kbentry class

        System.out.print("\nPlease enter a number for Total Impulse: " );   //Print message to enter 1. input
        double totalImpulse = input.totalImpulse1(); //Holds the variable  entered
        System.out.println("You have entered : " + totalImpulse); //Shows  the variable entered


        System.out.print("\nPlease enter a number for Average mass: " ); //Print message to enter 2. input
        double averageImpulse = input.averageImpulse2(); //Holds the variable entered
        System.out.println("You have entered : " + averageImpulse); //Shows the variable entered

        System.out.print("\nPlease enter a number for Time ejection charge fires: " ); //Print message to enter 3. input
        double timeEjectionChargeFires = input.timeEjectionChargeFires3(); //Holds the variable entered
        System.out.println("You have entered : " + timeEjectionChargeFires); //Shows the variable entered

        System.out.print("\nPlease enter a number for the Mass of the empty vehicle: " ); //Print message to enter 4. input
        double massEmptyVehicle = input.massEmptyVehicle4(); //Holds the variable entered
        System.out.println("You have entered : " + massEmptyVehicle); //Shows the variable entered

        System.out.print("\nPlease enter a number for the Mass of the engine: " ); //Print message to enter 5. input
        double engineMass = input.engineMass5(); //Holds the variable entered
        System.out.println("You have entered : " + engineMass); //Shows the variable entered

        System.out.print("\nPlease enter a number for the Mass of the fuel: " ); //Print message to enter 6. input
        double fuelMass = input.fuelMass6(); //Holds the variable entered
        System.out.println("You have entered : " + fuelMass); //Shows the variable entered




        CalculatingRocketFlightProfile calculations = new CalculatingRocketFlightProfile(totalImpulse,averageImpulse, timeEjectionChargeFires,
        massEmptyVehicle, engineMass, fuelMass); //Giving the object parameters required from constructor


            //Print out lines showing the result. 
            System.out.println("\nThe average mass of the vehicle: " +calculations.theAverageMassOfTheVehicle() /1000 + " g" +
                              "\nThe vehicles maximum velocity: " + calculations.theVehiclesMaximumVelocity() * 1000 + " m/s");

        //This is what I want to be saved and opened later. 

        

//kb 入口类(所有输入的方法相同,例如averageImpulse2、timeEjectionChargeFires3....等)

 import java.io.BufferedReader;
 import java.io.InputStreamReader;
 import java.io.IOException;


 public class kbentry //Class name

 double totalImpulse1() //Method for 1. input

 BufferedReader in = new BufferedReader(new InputStreamReader(System.in));   //Creates BufferedReader object for System.in

//Total Impulse entry
String strTotalImpulse = null;  // These must be initialised
double    intTotalImpulse = 0; //Setting it double

try 
  strTotalImpulse = in.readLine(); //Reads string value from the keyboard
 
catch (IOException ioe)   // ignore exception

   

try 
  intTotalImpulse = Double.parseDouble(strTotalImpulse);  // convert it to double
 
catch (NumberFormatException nfe)  
System.out.println("Error! Please enter a number!" + nfe.toString());  //Error message if its not a double

System.out.print("\nPlease enter a number for Total Impulse: "); //again ask for input again
return totalImpulse1(); //Returns value, so it can be re-entered


return intTotalImpulse; //return value

【问题讨论】:

【参考方案1】:

我自己在制作类似程序时遇到了这个问题。您将要使用 FileWriter,类似于下面的代码,我不知道您想要这个,但这里是如何将文件写入(和创建)到(现有)目录:

final File file = new File("C:\\path\\to\\dir");
file.createNewFile();
FileWriter fileOut = new FileWriter(file.getAbsoluteFile(), true);
fileOut.write("Here is where you write to the file";
/*you can write to the file again with out erasing the contents by
* using the .append() method*/ 
fileOut.close();

另外,您是在使用 eclipse,还是在 cmd 中进行编码。如果是这样,你应该得到日食。您还需要在 main 中导入 File (java.io) 和 FileWriter 类。

你应该把它放在这段代码的 sn-p 下:

//Print out lines showing the result. 
        System.out.println("\nThe average mass of the vehicle: " +calculations.theAverageMassOfTheVehicle() /1000 + " g" +
                          "\nThe vehicles maximum velocity: " + calculations.theVehiclesMaximumVelocity() * 1000 + " m/s");

    //This is what I want to be saved and opened later. 

像这样:

//Print out lines showing the result. 
        System.out.println("\nThe average mass of the vehicle: " +calculations.theAverageMassOfTheVehicle() /1000 + " g" +
                          "\nThe vehicles maximum velocity: " + calculations.theVehiclesMaximumVelocity() * 1000 + " m/s");
String theAverageMass = "The average mass of the vehicle: " +calculations.theAverageMassOfTheVehicle() /1000 + " g";
String theMaxVelocity = "\nThe vehicles maximum velocity: " + calculations.theVehiclesMaximumVelocity() * 1000 + " m/s"
    //This is what I want to be saved and opened later. 

final File file = new File("C:\\path\\to\\dir\\yourSaveFile.txt");
file.createNewFile();
FileWriter fileOut = new FileWriter(file.getAbsoluteFile(), true);
fileOut.write(theAverageMass+theMaxVelocity);
/*you can write to the file again with out erasing the contents by
* using the .append() method*/ 
fileOut.close();

你的主类应该是(带有适当的导入):

public class Main  //Master class


    public static void main( String args[] ) //Standard header for main  method
    


    kbentry input = new kbentry(); //Creates object of kbentry class

    System.out.print("\nPlease enter a number for Total Impulse: " );   //Print message to enter 1. input
    double totalImpulse = input.totalImpulse1(); //Holds the variable  entered
    System.out.println("You have entered : " + totalImpulse); //Shows  the variable entered


    System.out.print("\nPlease enter a number for Average mass: " ); //Print message to enter 2. input
    double averageImpulse = input.averageImpulse2(); //Holds the variable entered
    System.out.println("You have entered : " + averageImpulse); //Shows the variable entered

    System.out.print("\nPlease enter a number for Time ejection charge fires: " ); //Print message to enter 3. input
    double timeEjectionChargeFires = input.timeEjectionChargeFires3(); //Holds the variable entered
    System.out.println("You have entered : " + timeEjectionChargeFires); //Shows the variable entered

    System.out.print("\nPlease enter a number for the Mass of the empty vehicle: " ); //Print message to enter 4. input
    double massEmptyVehicle = input.massEmptyVehicle4(); //Holds the variable entered
    System.out.println("You have entered : " + massEmptyVehicle); //Shows the variable entered

    System.out.print("\nPlease enter a number for the Mass of the engine: " ); //Print message to enter 5. input
    double engineMass = input.engineMass5(); //Holds the variable entered
    System.out.println("You have entered : " + engineMass); //Shows the variable entered

    System.out.print("\nPlease enter a number for the Mass of the fuel: " ); //Print message to enter 6. input
    double fuelMass = input.fuelMass6(); //Holds the variable entered
    System.out.println("You have entered : " + fuelMass); //Shows the variable entered




    CalculatingRocketFlightProfile calculations = new CalculatingRocketFlightProfile(totalImpulse,averageImpulse, timeEjectionChargeFires,
    massEmptyVehicle, engineMass, fuelMass); //Giving the object parameters required from constructor


        //Print out lines showing the result. 
        System.out.println("\nThe average mass of the vehicle: " +calculations.theAverageMassOfTheVehicle() /1000 + " g" +
                          "\nThe vehicles maximum velocity: " + calculations.theVehiclesMaximumVelocity() * 1000 + " m/s");
        String theAverageMass = "The average mass of the vehicle: " +calculations.theAverageMassOfTheVehicle() /1000 + " g";
        String theMaxVelocity = "\nThe vehicles maximum velocity: " + calculations.theVehiclesMaximumVelocity() * 1000 + " m/s";
            //This is what I want to be saved and opened later. 

        final File file = new File("C:\\path\\to\\dir\\yourSaveFile.txt");
        file.createNewFile();
        FileWriter fileOut = new FileWriter(file.getAbsoluteFile(), true);
        fileOut.write(theAverageMass+theMaxVelocity);
        /*you can write to the file again with out erasing the contents by
        * using the .append() method*/ 
        fileOut.close();


    

【讨论】:

我正在使用 Notepad++ 编写代码,并在 CMD 中编译它。感谢您的代码,我会试一试并让您知道。我是在我的主要课程中使用它还是在单独的课程中使用它? 我不太清楚如何处理这段代码,你能告诉我应该在哪里包含它吗? 当然!请给我一点时间来弄清楚。我还没有完全阅读你的代码。 对不起,我的答案还没写完,我先走了,我会在一个小时左右发布。 我是否在 main 中或之外包含 final Final final = new File (etc...) 行?

以上是关于如何在java中保存和打开文件(在cmd中)的主要内容,如果未能解决你的问题,请参考以下文章

如何运行cmd

dos下怎么运行java程序

windows怎么打开命令提示符

第二篇:Dos下运行java程序

带有包的java程序怎么在cmd中运行?

如何用批处理打开文件