使用java.io.package/如何从变量读取数据并将其存储在文件中?

使用java.io.package/如何从变量读取数据并将其存储在文件中?,java,java-io,Java,Java Io,有人能给我一个提示,我如何从一个变量(一些字符串文件)中读取数据,这个变量保存我的随机计算,并将输出存储在一个文本文件中,可能还有一些处理它的功能 谢谢, 斯泰利扬我给你举了两个例子;第一种是读取文本文件,第二种是写入文本文件 import java.io.*; class FileRead { public static void main(String args[]) { try{ BufferedReader br = new Buffere

有人能给我一个提示,我如何从一个变量(一些字符串文件)中读取数据,这个变量保存我的随机计算,并将输出存储在一个文本文件中,可能还有一些处理它的功能

谢谢,
斯泰利扬

我给你举了两个例子;第一种是读取文本文件,第二种是写入文本文件

import java.io.*;
class FileRead {
    public static void main(String args[]) {
        try{
            BufferedReader br = new BufferedReader(new FileReader("textfile.txt"));
            String strLine;
            //Read File Line By Line
            while ((strLine = br.readLine()) != null)   {
               // Print the content on the console
               System.out.println (strLine);
            }
            //Close the input stream
            br.close();
         } catch (Exception e){//Catch exception if any
             System.err.println("Error: " + e.getMessage());
         }
     }
 }


import java.io.*;
class FileWrite {
    public static void main(String args[]) {
        String var = "var";
        try {
            // Create file 
            FileWriter fstream = new FileWriter("out.txt");
            BufferedWriter out = new BufferedWriter(fstream);
            out.write(var);
            //Close the output stream
            out.close();
        } catch (Exception e){//Catch exception if any
            System.err.println("Error: " + e.getMessage());
        }
    }
}

谢谢我这样做了,但找不到我的file.txt。我搜索了程序目录,但没有这个名称的文件,什么也没有。@StelyianStoyanov这可能是因为相对路径将文件放在了意外的地方。请尝试使用像“C:\\test.txt”这样的绝对路径,以便您可以找到/确认它。Riyad Kalla,谢谢您的回答,但我使用的是unix机器,在这种情况下,如何保存文件?谢谢类似于/home/rama/scripts/text.txt的内容非常感谢!工作正常,我可以对文件执行任何操作(在java中)