我正在尝试将2D数组打印到文件中

时间:2015-05-27 14:44:05

标签: java arrays file printing

我想将2D数组打印到桌面上的txt文件中。重要的是,输出的格式是在代码中,因为它代表行和席位。

代码:

package vaja15;
import java.util.*;
import java.io.PrintWriter;
import java.io.File;
import java.io.FileNotFoundException;

public class Vaja15 
{
    public static void main(String[] args) throws FileNotFoundException 
    {
        System.out.println("Vnesi velikost dvorane (vrste/sedezi):  ");
        Scanner sc = new Scanner(System.in);
        Random r  = new Random();
        int vrst = sc.nextInt();
        int sedezev = sc.nextInt(); 
        int [][] dvorana  = new int [vrst][sedezev];
        File  file = new File ("C:/users/mr/desktop/dvorana.txt");


        for(int i = 0; i<dvorana.length; i++)
        {
            System.out.println();
            for (int j = 0; j<dvorana.length; j++)
            {
                dvorana [i][j] = r.nextInt(3);  
                System.out.print(dvorana[i][j]);
                PrintWriter out = new PrintWriter(file);
                out.println(dvorana[i][j]);
                out.close();
            }   
        }
     }
 }

2 个答案:

答案 0 :(得分:1)

您不应该在循环中打开和关闭文件:在循环之前打开文件,编写数组,关闭文件。否则它会一遍又一遍地覆盖文件。

试试这个:

PrintWriter out = new PrintWriter(file);

for(int i = 0; i<vrst; i++)
{
    System.out.println();
    out.println();
    for (int j = 0; j<sedezev; j++)
    {
        dvorana [i][j] = r.nextInt(3);  
        System.out.print(dvorana[i][j]);          
        out.print(dvorana[i][j]);
    }   
}

out.close();

答案 1 :(得分:0)

尝试以下想法:

try {
  File file = new File(path);
  FileWriter writer = new FileWriter(file);
  BufferedWriter output = new BufferedWriter(writer);
  for (int[] array : matrix) {
    for (int item : array) {
       output.write(item);
       output.write(" ");
    }
    output.write("\n"); 
  }
  output.close();
} catch (IOException e) {

}