不读文件?

时间:2012-08-29 14:17:03

标签: java netbeans bufferedreader filereader filewriter

所以我想阅读一个文本文件,但由于一些奇怪的原因,它无法找到该文件。我之前使用过这些方法,因此我不知道为什么这不起作用有人可以帮帮我吗?

编辑:

抱歉,我遗漏了一大段信息,它可以在写入文件时找到文件,但是当它从中读取文件时却找不到。感谢你们所有人的帮助,抱歉浪费你的时间提问,我不需要答案......再次抱歉。

更多信息:

“Assets.txt”既在项目的根文件夹中,也在src / assetregistry中

程序运行时

“Assets.txt”将出现在那里

我得到的是来自readFromFile()方法中的catch异常的JOption messege

根据assetRegistry的属性,工作目录是

"C:\Users\Justin\Documents\NetBeansProjects\assetregistry\src\assetregistry"

感谢所有帮助过的人,尤其是Chris和Andrew Thompson。该程序现在可以使用,以下是更新版本。如果您愿意,可以随意复制。这真的是一个简单的程序。

主要课程:

package assetregistry;
import java.io.IOException;
import javax.swing.JOptionPane;

public class Assetregistry {

public static void main(String[] args) throws IOException {
    new Assetregistry();
}

assetArray aa = new assetArray();

public Assetregistry() throws IOException {
    aa.readFromFile ();
    char choice = 'Z';
    while (choice != 'X') {
        choice = menu();
        options(choice);
    }
}   

public char menu() {
    char ch = JOptionPane.showInputDialog("\t" + "Welcome to asset registry. Please input your choice" + "\n" + "A: Enter new asset" + "\n" + "B: Calculate depreciation and display" + "\n" + "X: Exit").toUpperCase().charAt(0);
    return ch;
}

private void options(char c) throws IOException {

    switch (c) {
        case 'A':
            aa.enterAsset();
            break;
        case 'B':
            aa.calculate();
            break;
        case 'X':
            System.exit(0);
            break;
    }
}
}

数组/方法类

package assetregistry;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.StringTokenizer;
import javax.swing.JOptionPane;

public class assetArray {

asset[] aArr = new asset[100];
private double year;
private double month;
private int count = 0;
Assetregistry AR;
String home = System.getProperty("user.home");
File userHome = new File(home);
File file = new File(userHome,"Assets.txt");

public assetArray() throws IOException {
}

public void enterAsset() throws IOException {

    int choice = JOptionPane.YES_OPTION;
    while (choice == JOptionPane.YES_OPTION) {
        String name = JOptionPane.showInputDialog("Enter asset name");
        double costP = Double.parseDouble(JOptionPane.showInputDialog("Enter the cost price of the asset"));
        int lSpan = Integer.parseInt(JOptionPane.showInputDialog("Enter the amount of years you wish to keep the asset"));
        double mBought = Double.parseDouble(JOptionPane.showInputDialog("Enter the month the asset was bought (As a number)"));
        double yBought = Double.parseDouble(JOptionPane.showInputDialog("Enter the year the asset was bought"));
        double depr = (1.00 / lSpan * 100.00);
        aArr[count] = new asset(name, costP, lSpan, yBought, mBought, depr);
        PrintWriter pw = new PrintWriter(new FileWriter(file, true));
        pw.println(aArr[count].toString());
        pw.close();
        count++;
        choice = JOptionPane.showConfirmDialog(null, " Do you want to enter another asset?", " Enter another asset?", JOptionPane.YES_NO_OPTION);
    }
}

public void calculate() {
    String name;
    int lSpan;
    double ybought;
    double mbought;
    double pValue;
    double Rate;
    double deprExp;
    double numYears;
    double fValue;
    double accDepr;
    String[] mnth = new String[12];
    mnth[0] = "January";
    mnth[1] = "February";
    mnth[2] = "March";
    mnth[3] = "April";
    mnth[4] = "May";
    mnth[5] = "June";
    mnth[6] = "July";
    mnth[7] = "August";
    mnth[8] = "September";
    mnth[9] = "October";
    mnth[10] = "November";
    mnth[11] = "December";

    if (count > 0) {
        year = Integer.parseInt(JOptionPane.showInputDialog("Enter the year you wish to calculate depreciation for"));
        month = Integer.parseInt(JOptionPane.showInputDialog("Enter the month you wish to calculate depreciation for"));
        int m = (int) month;
        int y = (int) year;
        System.out.println("Asset regestry" + "\t" + mnth[m-1] + "  " + y);
        for (int i = 0; i < count; i++) {
            name = aArr[i].getName();
            lSpan = aArr[i].getLifeSpan();
            ybought = aArr[i].getyBought();
            mbought = aArr[i].getmBought();
            pValue = aArr[i].getCostP();
            Rate = aArr[i].getDeprR();
            int m2 = (int) mbought;
            int y2 = (int) ybought;
            deprExp = pValue - (pValue * ((1.00 - ((Rate))) * 1.00 / 100.00));
            numYears = (year + (month / 12.00)) - (ybought + mbought / 12.00);
            fValue = pValue * (1.00 - (((Rate) * (numYears)) / 100.00));
            if (fValue <= 0.00) {
                fValue = (int) 1;
            }
            accDepr = pValue - fValue;
            System.out.println("\n" + "Asset:  " + name);
            System.out.println("Life span:  " + lSpan + "yrs");
            System.out.println("Cost price:  " + "R" + pValue);
            System.out.println("Date acquired:  " + mnth[m2-1] + "  " + y2);
            System.out.println("Depreciatin rate (p.a.):  " + Rate + "%");
            System.out.println("Depreciation(p.a.):  R" + deprExp);
            System.out.println("Accumulated depreciation:  R" + accDepr);
            System.out.println("Current book value:  R" + fValue);
            System.out.println("_________________________________________");
        }
    } else {
        JOptionPane.showMessageDialog(null, "There are no assets in memory", "NO ASSETS!", JOptionPane.ERROR_MESSAGE);
    }

}

/**
 *
 */
public void readFromFile() {
    String line = "";
    try {
        BufferedReader fr = new BufferedReader(new FileReader(file));
        line = fr.readLine();
        while (line != null) {
            StringTokenizer stk = new StringTokenizer(line, "#");
            String name = stk.nextToken();
            double costP = Double.parseDouble(stk.nextToken());
            int lSpan = Integer.parseInt(stk.nextToken());
            double yBought = Double.parseDouble(stk.nextToken());
            double mBought = Double.parseDouble(stk.nextToken());
            double deprR = Double.parseDouble(stk.nextToken());
            aArr[count] = new asset(name, costP, lSpan, yBought, mBought, deprR);
            count++;
            line = fr.readLine();

        }
        fr.close();
    } catch (Exception e) {
        JOptionPane.showMessageDialog(null, "There is a file missing.", "FILE MISSING!", JOptionPane.ERROR_MESSAGE);
    }
}
}

资产类

package assetregistry;

/**
 *
 * @author Justin
 */
public class asset {

private String name;
private double costP;
private int lifeSpan;
private double yBought;
private double mBought;
private double deprR;

public asset(){
}

public asset(String name, double costP, int lifeSpan, double yBought, double mBought, double deprR) {
this.name = name;
this.costP = costP;
this.lifeSpan = lifeSpan;
this.yBought = yBought;
this.mBought = mBought;
this.deprR = deprR;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public double getCostP() {
return costP;
}

public void setCostP(double costP) {
this.costP = costP;
}

public int getLifeSpan() {
return lifeSpan;
}

public void setLifeSpan(int lifeSpan) {
this.lifeSpan = lifeSpan;
}

public double getyBought() {
return yBought;
}

public void setyBought(double yBought) {
this.yBought = yBought;
}

public double getmBought() {
return mBought;
}

public void setmBought(double mBought) {
this.mBought = mBought;
}

public double getDeprR() {
return deprR;
}

public void setDeprR(double deprR) {
this.deprR = deprR;
}

@Override
public String toString ()
{
String stg = "";
stg += name + "#" + costP + "#" + lifeSpan + "#" + yBought + "#" + mBought + "#" + deprR + "#";
return stg;
}   
}

2 个答案:

答案 0 :(得分:2)

String home = System.getProperty("user.home");
System.out.println("User home directory is: " + home);
File userHome = new File(home);
// Put files in a known and reproducible path!
File file = new File(userHome, "Assets.txt");

答案 1 :(得分:2)

这取决于您在文件系统中放置“Assets.txt”的位置。如果您从netbeans内部运行代码,则行:

File file = new File("Assets.txt");

将在项目的根文件夹中查找该文件,例如* / NetBeansProjects / INSERT_PROJECT_NAME /(如果你不是那么它将在运行应用程序的同一目录中查找文件)。我注意到你有这行:

URL url = AR.getClass().getResource("/Assets.txt");

但你永远不会在你的代码中使用url。您是否尝试在与“Assetregistry”类相同的目录中查找该文件,并忘记使用url指定位置?如果是这种情况,则从名称的开头删除“/”并构造如下文件:

URL url = Assetregistry.class.getResource("Assets.txt");
File file = new File(url.toURI());

希望这有帮助:)