【问题标题】:Java: Read/Write a File and moreJava:读/写文件等等
【发布时间】:2014-03-27 23:26:57
【问题描述】:

我创建了一个包含 2 个方法的类,这些方法可以处理写入文件或读取文件。

我想出了这样的东西:

package YBot;
import java.io.*;



public class FollowerChecker {



public static StringBuilder sb;


    static String readFile(String fileName) throws IOException {
        BufferedReader br = new BufferedReader(new FileReader(fileName));
        try {
            sb = new StringBuilder();
            String line = br.readLine();

            while (line != null) {
                sb.append(line);
                sb.append("\n");
                line = br.readLine();

            }
            return sb.toString();
        } finally {
            br.close();

        }
    }



    public static void Writer() {

        FileWriter fw = null;

        try {
            fw = new FileWriter("donottouch.txt");
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }


        StringWriter sw = new StringWriter();
        sw.write(TwitchStatus.totalfollows);


        try {
            fw.write(sw.toString());
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }


        try {
            fw.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

现在我的问题是:

如果“donottouch.txt”文件尚不存在或为空以在其中写入“0”,我如何添加创建“donottouch.txt”文件的功能?当我的程序启动时,它将读取文件中的数字,然后,如果数字改变,它将重写它。因此,最好是一旦它尝试阅读并且它不存在,它就会立即创建它并重新阅读它。希望some1可以给我任何例子=)

【问题讨论】:

标签: java bufferedreader java-io


【解决方案1】:

我是这样处理的:

public static boolean checkIfExists(String path) {
    if (!new File(path).exists()) {
        return false;
    } else {
        return true;
    }
}

public static String readFile(String file) throws IOException {
    BufferedReader reader = new BufferedReader(new FileReader (file));
    String line;
    StringBuilder sb = new StringBuilder();

    while( ( line = reader.readLine() ) != null) {
        sb.append( line );
    }
    reader.close();
    return sb.toString();

}

public static void writeFile(String path) throws FileNotFoundException, 
                                                UnsupportedEncodingException {
    PrintWriter writer = new PrintWriter(path, "UTF-8");
    writer.println("0");
    writer.close();
    return;
}

public static void main(String args[]) {
    /*Gets absolute path to your project folder, assuming that is where
     * you are storing this text file. Otherwise hard code your path
     * accordingly.
     */
    File file = new File("");
    String fileGet = file.getAbsolutePath();
    StringBuilder sb = new StringBuilder();
    String path = sb.append(fileGet.toString() + "/donottouch.txt").toString();

    String result=null;

    if(!checkIfExists(path)) {
        try {
            writeFile(path);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        System.out.println("File created: 'donottouch.txt'");

    } else {
        try {
            result = readFile(path);
        } catch (IOException e) {
            e.printStackTrace();
        }

        if( result.length() == 0 ) {
            try {
                writeFile(path);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            System.out.println("File amended: 'donottouch.txt'");
        }
        System.out.println("File exists: 'donottouch.txt'");
    }
}

显然,我创建了一个主类并在一个类之外完成了所有这些工作,这与您不同,但集成起来应该非常简单。这是基于您将“donottouch.txt”存储在项目的源文件中的假设,但是您可以轻松地将获取绝对路径的代码更改为您正在查找的文件夹的硬编码路径.希望这会有所帮助!

【讨论】:

  • 那么我将如何调用您的代码将我想要的字符串写入文件?在我的代码中,我刚刚调用了 FollowerChecker.Writer();它确实将字符串“totalfollows”写入文件。我只是不明白你的“路径”。该文件位于项目源中。
  • 路径是文件的绝对路径。它只是一个结构为“/Users/YourName/PathToYourProjectFolder/.../donottouch.txt”的字符串,因此传入路径本质上是传入文件。这样,您不必对整个路径进行硬编码,以防文件夹移动。 checkIfExists() 方法正在检查项目路径中是否存在“donottouch.txt”文件,如果存在,则通过 readFile() 方法读取。从这里开始,如果为空或不存在,则通过 writeFile() 方法在内部写入“0”。
  • 我回答你的问题了吗?您可能无法使用我的框架的 exact 结构,但可以将其中的方法合并到您的代码中。希望这至少可以帮助一些:)
  • 好吧,我对 java 还是很陌生,所以我不明白这一切.. 但我想我必须尝试一下。只是想再问问它是否不起作用。谢谢。
  • 好吧,我太傻了,我的东西无论如何也不管用.. :(
猜你喜欢
  • 2023-04-03
  • 1970-01-01
  • 1970-01-01
  • 2012-06-14
  • 1970-01-01
  • 1970-01-01
  • 2011-07-22
  • 1970-01-01
相关资源
最近更新 更多