无法在JAVA中将输出写入文本文件

Man*_*noo 2 java file

我正在尝试将数字1-10的平方输出到名为Squares的文件中,但我对该OutputStream.print(i+"\t"+(i*i));部件有错误.印刷品有下划线,我不明白为什么.请帮我.

这是代码:

import java.util.*;
import java.io.*;
public class Number1 {

    public static void main(String[] args) throws FileNotFoundException {
        FileOutputStream fos = new FileOutputStream("Squares.txt");
        PrintWriter square;

        try{
            square = new PrintWriter(fos);     
        } catch (Exception e) {
            System.out.print("Could not create/open file");
            System.exit(0);
        }

        for(int i=1; i<=10; i++)
        {
            OutputStream.print(i+"\t"+(i*i));
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

完整解决方案

import java.io.*;
public class Number1 {

public static void main(String[] args) throws FileNotFoundException {
   FileOutputStream fos = new FileOutputStream("Squares.txt");
   PrintWriter square = null; 

   try{
       square = new PrintWriter(fos);     

   }

   catch (Exception e)
   {
       System.out.print("Could not create/open file");
       System.exit(0);
   }

   for(int i=1; i<=10; i++)
   {
      square.print(i+"\t"+(i*i));
   }
  square.close();

  }
}
Run Code Online (Sandbox Code Playgroud)

Era*_*ran 6

OutputStream没有print方法,即使它有一个,它可能不是一个静态的方法.

使用您的PrintWriter实例写入文件.

public static void main(String[] args) throws FileNotFoundException 
{
    FileOutputStream fos = new FileOutputStream("Squares.txt");
    try{           
        PrintWriter square = new PrintWriter(fos);     
        for(int i=1; i<=10; i++) {
            square.print(i+"\t"+(i*i));
        }
        square.close ();
    } 
    catch (Exception e) {
        System.out.print("Could not create/open file");
        System.exit(0);
    }
}
Run Code Online (Sandbox Code Playgroud)