2016-06-26 7 views
1

У меня есть текстовый файл, в который программа будет иметь правильные данные. Я хочу дать максимальное количество символов линии и убедиться, что строка будет содержать только это количество символов. (Так оно и должно автоматически переключаться на следующую строку, если количество символов достиг)Как заставить программу читать символы в строке в файле и переходить в следующую строку, если достигнут определенный счетчик символов?

// мой код

public static void main(String[] args) { 

    // The name of the file to open. 
    String fileName = "file.txt"; 
    int counter = 0; 

    // This will reference one line at a time 
    String line = null; 
    FileReader fileReader = null; 
    int chars = 0; 
    int max = 55; 
    try { 
     // FileReader reads text files in the default encoding. 
     fileReader 
       = new FileReader(fileName); 

     // Always wrap FileReader in BufferedReader. 
     BufferedReader bufferedReader 
       = new BufferedReader(fileReader); 

     while ((line = bufferedReader.readLine()) != null) { 
      counter++; 
      if (counter == 1) { 
       chars += line.length(); 
       System.out.println(chars); 
       System.out.println(line); 
       if (chars == max) { 
       //if max characters reached jump to the 7th line 
        counter += 6; 
       } 
       System.out.println(counter); 
      } 
     } 

    } catch (FileNotFoundException ex) { 
     ex.printStackTrace(); 
    } catch (IOException ex) { 
     ex.printStackTrace(); 
    } 
} 

}

Как я могу изменить этот код, чтобы он автоматически прыгать в 7-я строка, когда достигнуто максимальное количество символов (55)?

ответ

2

Я думаю, что у вас уже была правильная идея, отслеживая текущую позицию, но может быть проще просто создать подстроку, если ваша текущая строка превышает желаемый размер, а не отслеживает, сколько символов было прочитано до сих пор :

import java.io.BufferedReader; 
import java.io.FileInputStream; 
import java.io.FileNotFoundException; 
import java.io.IOException; 
import java.io.InputStreamReader; 
import java.util.logging.Level; 
import java.util.logging.Logger; 


public class StackQuestions { 

    /** 
    * @param args the command line arguments 
    */ 
    public static void main(String[] args) { 
     FileInputStream fstream = null; 
     int max = 55; 
     int desiredIndex = 0; //the line number you want to reach 
     int currentIndex=0; //your current line number 

     try { 
      // TODO code application logic here 
      fstream = new FileInputStream("file.txt"); 
      BufferedReader br = new BufferedReader(new InputStreamReader(fstream)); 
      String strLine; 

      //Read File Line By Line 
      while ((strLine = br.readLine()) != null) { 
       // Print the content on the console if the string length is larger than the max, after creatng a substring 
       if(strLine.length()> max && currentIndex==desiredIndex){ 
       strLine=strLine.substring(0, max); 
       desiredIndex=currentIndex+6; 
       System.out.println(strLine); 
       } 

       currentIndex++; 
      } 
     } catch (FileNotFoundException ex) { 
      Logger.getLogger(StackQuestions.class.getName()).log(Level.SEVERE, null, ex); 
     } catch (IOException ex) { 
      Logger.getLogger(StackQuestions.class.getName()).log(Level.SEVERE, null, ex); 
     } finally { 
      try { 
       fstream.close(); 
      } catch (IOException ex) { 
       Logger.getLogger(StackQuestions.class.getName()).log(Level.SEVERE, null, ex); 
      } 
     } 

    } 

} 

в любом случае надеюсь, что это помогает немного, если не дай знать, и я постараюсь помочь :) удачи на программировании