【问题标题】:buffered writer now writing to filebufferedwriter 不写入文件
【发布时间】:2016-08-05 01:26:16
【问题描述】:

有人可以指出我为什么不写入 .txt 文件的正确方向吗?

这是我打印时得到的输出。我无法弄清楚代码中的错误在哪里。从输出中可以看出。它看起来在第一个循环中一切正常。我的第一个问题是为什么它不将“val 5”写入 .txt 文件?我的第二个问题是为什么它在第二个矩阵之后不再走?

我是一名学生,希望对我的代码有任何反馈,以使其变得更好。请尽可能多地提出建议。

输入:

1
5
3
3 -2 4
-1 5 2
-3 6 4

打印时的输出:

Size:1
insert 5
len: 1 
size2 1
val5 
Size:3 
insert 3
insert -2
insert 4
insert -1
insert 5
insert 2
insert -3
insert 6
insert 4
len: 9

.txt 文件的输出:

Matrix read: 
---------------------------------------

Matrix read: 
---------------------------------------

代码如下:

import java.util.*;
import java.lang.*;
import java.io.*;

public class Driver{


public static void main(String[] args) {

  //initialize variables 
  String filepath;
  BufferedWriter bw = null;
  String toRead = "";
  CustomList[] arrayForList;
  CustomList listToBuild;



  try {
     System.out.println("To find the determinant of a Matrix, please enter the file below!");
     System.out.println("Please enter the file path of the txt file:\n");

     //read user input
     Scanner user_input = new Scanner(System.in);
     filepath = user_input.next();

     //print out the file path for user to confirm the 
     //correct file path was entered
     System.out.println("Filepath read: " + filepath);
     System.out.println("");

     //finds the spot of the "." in .txt
     int extCounter = filepath.indexOf('.');
     String Output_Path = filepath.substring(0, extCounter);

     //close the scanner
     user_input.close();


     //Specify the file name and path here
     //the below code allows the user to enter one path
     //and get the output file at the same path
     //without having to enter it twice
     String OutFile;
     OutFile = Output_Path.concat("_Output5_File.txt");
     File file = new File(OutFile);

     // This logic will make sure that the file 
     // gets created if it is not present at the
     // specified location
     if (!file.exists()) {
        file.createNewFile();
     }

     //initialize array to hold strings
     String [] arrayToHoldInts = new String [100];


     //sets up filewriter to write output
     FileWriter fw = new FileWriter(file);
     bw = new BufferedWriter(fw);

     // open input stream test.txt for reading purpose.
     BufferedReader br = new BufferedReader(new FileReader(filepath));

     String input = "";
     input = br.readLine();
     int sizeOfArrayToStore = 0;
     while (input != null) {

        //below 2 lines get the size of the matrix
        sizeOfArrayToStore = Integer.parseInt(input);
        System.out.println("Size:" + sizeOfArrayToStore);

        //reads the next line after getting the size
        input = br.readLine();

        //checks for blanks and continues on error
        if (input.length() == 0){
           continue;
        }


        String [] stringSplitterForBR = null;
        arrayForList = new CustomList [sizeOfArrayToStore * sizeOfArrayToStore];

        //for loop to add ints parse the string that the
        //bufferred reader reads in. there is another nested
        //for loop to add each int that is parsed into a new
        //node for to build the list
        for (int i = 0; i < sizeOfArrayToStore; i++){
           listToBuild = new CustomList();
           stringSplitterForBR = input.split(" ");


           int tracker = 0;
           int valueToInsert = 0;   

           //for loop parses the ints and adds them into nodes
           //from the CustomList class
           for(int j = 0; j < sizeOfArrayToStore; j++) {
              valueToInsert = Integer.parseInt(stringSplitterForBR[tracker]);
              System.out.println("insert " + valueToInsert);
              listToBuild.addToList(valueToInsert);
              tracker++;
           }

           arrayForList[i] = listToBuild;
           input = br.readLine();

        }
        //Compute the deterimant using the same formula from 
        //Lab2


        int length = arrayForList.length;
        System.out.println("len: " + length);

        //print out the results to a .txt file


        bw.write("Matrix read: ");
        bw.newLine();
        bw.write("------------------" +
              "---------------------");
        bw.newLine();
        bw.flush();

        int size2 = 0;
        int valueToPrint;
        for (int x = 0; x < length; x++){

           listToBuild = arrayForList[x];
           size2 = listToBuild.sizeOfList();
           System.out.println("size2 " + size2);
           for (int y = 0; y < size2; y++) {

              valueToPrint = listToBuild.ValueOfNode(y);
              bw.write(valueToPrint);
              System.out.println("val" + valueToPrint);
              bw.flush();

           }
           bw.newLine();
        }


     }  
     bw.close();


  } catch (Exception e) {
     e.printStackTrace();
  }

 }
}

【问题讨论】:

  • 提示:你到处都在违反 java 风格的约定。这使得经验丰富的 Java 编码人员很难阅读您的代码。不要在变量名或类名中使用 _。变量名是camelCase;他们总是以小写字母开头。等等。你最好开始习惯这样的规则......就像现在一样。然后:不要将所有代码放入一个方法中。而是:写很多小方法;并且每个方法只做一个的事情(所以,请阅读单层抽象原理)。
  • file.exists())/file.createNewFile() 逻辑确实会“确保在指定位置不存在文件时创建文件”,但下面的new FileWriter() 调用也会如此。不要编写冗余代码。删除它。

标签: java bufferedwriter


【解决方案1】:

BufferedWriter 上的write 方法与PrintStream 上的println 方法具有非常不同的语义(System.outPrintStream)。例如,您可以使用 int 值作为参数调用 println 并将其打印为数字,但 write 方法将其解释为单个字符的 unicode,并且只会写入单个字符 -在您的代码中,对于“val 5”,这是数值为 5 的 unicode 字符。

您的解决方案:将 BufferedWriter 替换为 PrintWriter 并在您想要打印时使用 PrintWriter.println 方法 - 它与 System.out 上的 println 方法具有相同的语义。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-02-08
    • 1970-01-01
    相关资源
    最近更新 更多