【问题标题】:save regular data to file将常规数据保存到文件
【发布时间】:2012-12-20 15:09:03
【问题描述】:

我是java新手! 我使用此代码将数据写入 .txt 文件:

try { 
String content = "This is the content to write into file";
File file = new File("/users/mkyong/filename.txt");

// if file doesnt exists, then create it

if ( !file.exists() ) {
    file.createNewFile();
}
FileWriter fw = new FileWriter( file.getAbsoluteFile() );
BufferedWriter bw = new BufferedWriter( fw );
bw.write( content );
    bw.NewLine();
bw.close();
System.out.println("Done");
} catch (IOException e) {
e.printStackTrace();
}

名字姓氏注册号

乔

最大

1238

我想将每个数据存储在其名称下方:

我想要这样:

FName LName Reg_Num

乔最大 1238

谢谢!

【问题讨论】:

  • 有什么问题?顺便说一句,您探索 Java 真是太好了。一旦你知道 IO 是如何工作的,你就可以使用 commons.apache.org/io 项目中的 FileUtils.writeStringToFile(file, string); 之类的东西。
  • 代码怎么能用这个“bw.NewLine();”编译
  • 问题是 joe 和 max 和 number 应该正好在 firstname 和 lastname 和 reg_num 之下。但是它们每个都在一个新行中,如果我不使用换行方法,名字和姓氏将分别连接!

标签: java file


【解决方案1】:

该代码应将“这是要写入文件的内容”输出到文本文件中。这些名字是从哪里来的?

用于 Java 中的制表 see this topic。

【讨论】:

  • 这些名字来自一个简单的形式。
  • 不可能从您发布的代码中推断出这么多。无论如何,@parvin 似乎已经度过了把它布置得很整齐的麻烦:)
【解决方案2】:

您可以使用 \t 在字段之间添加选项卡。示例代码可能类似于:

    try {
        String firstName = "Joe";
        String lastName = "Doe";
        String regNum = "123";

        File file = new File("/home/parvin/Desktop/filename.txt");

        if (!file.exists()) {
            file.createNewFile();
        }

        FileWriter fw = new FileWriter(file.getAbsoluteFile());
        BufferedWriter bw = new BufferedWriter(fw);
        bw.write("FirstName\t LastName\t RegNum\t \n");
        bw.write(firstName + "\t" + lastName + "\t" + regNum + "\t" + "\n");
        bw.newLine();
        bw.close();

        System.out.println("Done");

    } catch (IOException e) {
        e.printStackTrace();
    }

【讨论】:

  • @APoliteBoy 如果您对它感到满意,请不要忘记接受答案。 :-)
猜你喜欢
  • 2019-07-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-02-08
  • 2017-10-25
相关资源
最近更新 更多