简体   繁体   English

Java:将输出打印到文本文件

[英]Java: Printing output to a text file

I am a beginner in coding.我是编码初学者。 I am in an Intro to Programming and Algorithms course in my college.我在我的大学学习编程和算法入门课程。 My professor and I cannot figure out how to fix this code.我的教授和我无法弄清楚如何修复此代码。 I am trying to output to a file from another file.我正在尝试从另一个文件输出到一个文件。 The new file is created, but remains empty.新文件已创建,但仍为空。 Any help or input would be greatly appreciated!任何帮助或输入将不胜感激! Thanks!谢谢!

import java.util.Scanner;
import java.io.PrintWriter;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
public class Part3 {
public static void main(String[] args) throws IOException
{
    int i = 0;

    FileInputStream fileIn = null;
    Scanner file = null;
    double input = 0;

    FileOutputStream fileOut = null;
    PrintWriter file2 = null;

    System.out.println("Opening file LabInput.txt.");
    fileIn = new FileInputStream("LabInput.txt");
    file = new Scanner(fileIn);

    fileOut = new FileOutputStream("LabOutput.txt");
    file2 = new PrintWriter(fileOut);

    while (file.hasNext())
    {
        input = file.nextDouble();
        file2.println("test");

            if(i % 3== 0)
            {
                 file2.println("");
                 i++;
            }
        file2.printf("%10.3f", input);
   }

    file2.println("");
    file2.println("Closing file LabInput.txt.");
    fileIn.close();
    fileOut.close();

}}

Add file2.close();添加file2.close(); at the end of your program.在你的程序结束时。 OutputStreams often write to a buffer instead of the actual destination (here the file). OutputStreams通常写入缓冲区而不是实际目标(此处为文件)。 This buffer is flushed when its full.这个缓冲区在它满时被刷新。 To ensure that everything is written to the file, you have to call close() .为确保所有内容都写入文件,您必须调用close()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM