小编典典

Java输出到文本文件?

java

所以我在打印输出时遇到麻烦。我理解这个概念,但是当涉及到这个问题时,这有点奇怪。我尝试了不同的打印行,所有这些行在控制台窗口中都给我不同的结果。我仍在尝试不同的方法,但即时通讯开始用尽想法。谢谢,非常感谢!

这就是我想要的预期输出。

1
1, 2, 3, 4

当我尝试println时,它对output.println(data [0]);

1
, 2, 3, 4

当我进行常规打印时

1, 2, 3, 4

这是文本文件打印方法`

    public class JavaApplication1 {

  static int[] Array(int[] data) {

      int size = 1;
      if (data !=null) {
          size = 1 +data.length;
      }
      return new int [size];
  }

  private static int[] addToArray(int[] data, int x) {
      int[] array2 = Array(data);
      if(data !=null) {
          System.arraycopy(data,0,array2,0,data.length);
      }
      array2[array2.length - 1] = x;
      return array2;
  }
  private int[] data;

  public JavaApplication1 (int[] data, int x) {
      this.data = addToArray(data, x);      
  }
  public void printall() {
      System.out.print(data[0]);
      for (int i = 1; i < data.length; i++) {
          System.out.printf(", %d", data[i]);

      }
      System.out.println();
  } public void text() {
    try {
           PrintWriter output =  new PrintWriter("test.txt");
           output.print(data[0]);
           for (int i = 1; i < data.length; i++) {
               output.printf( ", %d", data[i]);
               output.flush();
           }
    } catch (Exception ex) {

    }


  }


    public static void main(String[] args) {
        int[] in = {1,2,3};
        int[] test = {1,2,3};

        int l = 4;
        int x = 4;

        JavaApplication1 a = new JavaApplication1(null, 1);
        a.printall();
        JavaApplication1 b = new JavaApplication1(in, x);
        b.printall();


        JavaApplication1 c = new JavaApplication1(null, 1);
        c.text();
        JavaApplication1 d = new JavaApplication1(test, l);
        d.text();




    }

}

阅读 292

收藏
2020-11-30

共1个答案

小编典典

试试这个 :

public void text() {
        try {
            PrintWriter output = new PrintWriter("test.txt");
            output.println(data[0]);
            for (int i = 0; i < data.length; i++) {
                if (i != (data.length - 1)) {
                    output.printf("%d, ", data[i]);
                } else {
                    output.printf("%d", data[i]);
                }
                output.flush();
            }
        } catch (Exception ex) {

        }

    }
2020-11-30