2016-08-05 2 views
1

Может ли кто-нибудь указать мне в правильном направлении, почему это не записывается в .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(); 
    } 

} 
} 
+3

Подсказка: вы нарушаете правила стиля java повсюду. Это делает очень трудным для опытных java-кодеров читать ваш код. Не используйте _ в именах переменных или классов. Имена переменных - camelCase; и они начинаются с нижнего регистра всегда. И так далее. Вы лучше приучитесь к таким правилам ... как сейчас. Затем: не помещайте весь свой код в один метод. Вместо этого напишите много маленьких методов; и каждый метод делает только одну вещь (так, читайте об одном слое принципа абстракции). – GhostCat

+0

Логика 'file.exists())/file.createNewFile()' действительно будет «убедиться, что файл будет создан, если он не указан в указанном месте», но так же будет выполняться следующий «новый вызов FileWriter()» , Не пишите избыточный код. Удали это. – EJP

ответ

2

Метод write на BufferedWriter имеет очень разную семантику от println метода на PrintStream (System.out - PrintStream). Например, вы можете вызвать println с значением int в качестве аргумента, и он будет печатать его как число, но метод write интерпретирует это как Юникод одного символа и будет писать только один символ - в вашем коде, для " вал 5" , это юникода символ с числовым значением 5.

Раствор для вас: заменить BufferedWriter с PrintWriter и использовать метод PrintWriter.println всякий раз, когда вы хотите напечатать - он имеет ту же семантику, что и println метода на System.out.

Смежные вопросы