文件I/O投资组合说明



因此,对于学校项目,我必须编写一个文件I/O组合。

目标是使用PrintWriter将乘法表写入.txt文件。

我已经完成了一部分,现在我有点迷失了方向。这是我到目前为止的代码:

package lesson6;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
public class DataWriter {
//multiplication table
void multi() {
int[][] table = new int[10][10];
    for(int row = 0; row < table.length; row++) {
        for(int col = 0; col< table[row].length; col++) {
        table[row][col]= (row+1) * (col+1);
        System.out.print((row+1) + "X" + (col+1) + " = " + table[row][col] + " ");
        System.out.print(" ");
        }
    }
}


public static void main(String[] args) {
    java.io.File File = new java.io.File("data.txt");
    try {
        System.out.println("Writing to file.");
        File file = new File ("C:/Users/fjldjsafj/workspace/lesson6/data.txt");
        PrintWriter p = new PrintWriter(File);
        p.println();
    } catch (FileNotFoundException e) {
        //e.printStackTrace();
        System.out.println("Sorry, file not found.");
    }
    System.out.println("Finished writing to file.");
    }
}

请告诉我我做错了什么,因为我现在不知道该怎么办!很抱歉,如果它很难阅读或理解。。。任何关于下一步的提示都将非常有用!

事先非常感谢。

您可以从Java文档中了解有关类PrintWriter的更多信息。

由于您正试图将乘法表写入.txt文件,因此应该打开一个输出流。

试着使用这样的东西:

...
String yourFileName = "C:\yourFileName.txt";
PrintWriter outputStream = null;
try
{
    outputStream = new PrintWriter(yourFileName);
} 
catch (FileNotFoundException e) 
{
    System.out.println("Sorry, file not found.");
}

然后添加您的代码以尝试写入该文件。一定要测试一下。

之后,当您完成对文件的写入时,关闭输出流是很重要的:

outputStream.close();

希望这能有所帮助。

最新更新