请问,用java,如何从文件中读入我指定长度的字符串?谢谢!
展开全部
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class ReadFileByLength {
/**
* @param args
* @throws IOException
*/
public static void main(String[] args) throws IOException {
String file = "test.txt";//文件
final int length = 1000;//指定的长度
StringBuilder sb = new StringBuilder();
BufferedReader bf = new BufferedReader(new FileReader(file));
while(sb.length() <= length){
String content = bf.readLine();
if(content == null){
break;
}
sb.append(content);
}
bf.close();
String expectedStr = sb.substring(0, length).toString();
System.out.println("The string you want is: " + expectedStr);
}
}
import java.io.FileReader;
import java.io.IOException;
public class ReadFileByLength {
/**
* @param args
* @throws IOException
*/
public static void main(String[] args) throws IOException {
String file = "test.txt";//文件
final int length = 1000;//指定的长度
StringBuilder sb = new StringBuilder();
BufferedReader bf = new BufferedReader(new FileReader(file));
while(sb.length() <= length){
String content = bf.readLine();
if(content == null){
break;
}
sb.append(content);
}
bf.close();
String expectedStr = sb.substring(0, length).toString();
System.out.println("The string you want is: " + expectedStr);
}
}
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询