作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我有一个文本文件,程序会将数据正确保存到该文件中。我想为一行指定最大字符数,并确保一行仅包含该数量的字符。 (所以当字符数达到时它应该自动切换到下一行)
//我的代码
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();
}
}
}
如何修改此代码,以便在达到最大字符数(55)时自动跳转到第 7 行?
最佳答案
我认为通过跟踪当前位置,您已经有了正确的想法,但如果当前行超出了所需的大小,则创建一个子字符串可能更容易,而不是跟踪到目前为止已读取的字符数:
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);
}
}
}
}
无论如何,希望这能有所帮助,如果不是让我知道的话,我会尽力帮助:)祝你编程好运
关于java - 如何让程序读取文件中一行的字符,达到一定字符数后跳转到下一行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38036033/
我是一名优秀的程序员,十分优秀!