8.1 Javapython 按行读取文件文件:有多少种方法

java怎样读取文件所有内容,主要是跳行问题?谢谢了_百度知道
java怎样读取文件所有内容,主要是跳行问题?谢谢了
我要读取1.txt文件中的所以内容,放到String类型中, 内容如下:
dfgdfga2254
说明文件有换行,问题也就在这?
希望能得到String的内容是”dfgdfga2254dfa@#%#$%”
我想在一行一行的读取字符,然后在用String的concat的方法把所以的行加在一起...
如果是字符流文件。可以使用java.nio.file.Files类的readAllLines将所有内容读到一个List&String&里Google Guava库也提供了类似的功能com.google.common.io.Filesstatic StringtoString(File file,
Charset charset)
Reads all characters from a file into a String, using the given character set.
采纳率:44%
来自团队:
d.txt&))用BufferedReader 就行了
BufferedReader reader = new BufferedReader(new FileReader(&quot:\&#92!= null) {
str = str.concat(line);1;
String line =
while ((line = reader.readLine())
本回答被提问者采纳
mport java.** * 2008;
reader = new BufferedReader(new java./ TODO 自动生成方法存根
S public static String readFileByLines(java./ TODO Auto-generated catch block
e.printStackTrace();
try {结果为.Fimport java.io!= null) {
fullString.append(tempString);
return fullString.toString(); TODO Auto-generated catch block
e.FileNotFoundException.printStackTrace();import java.io.IOE&#47.printStackTrace().BufferedRimport java.io.println(&
} catch (IOException e) {
&#47.String tempString =
while ((tempString = reader.readLine()) != null) {
reader.09.22 * 读文件工具类 * @author 韩卫召 */public class FileReader { /
BufferedReader reader =+FileR
} catch (IOException e) {
} finally {
}public static void main(String[] args) {
&#47:\&#92. TODO Auto-generated catch block
e.readFileByLines(&quot.close():&quot.lang.StringBuffer fullString =new StringBuffer();
java.lang.FileReader(file));
} catch (IOException e) {
/&#47.printStackTrace().close();
} catch (FileNotFoundException e) {
e.String filename) {
File file = new File(filename);*
* 传入参数 String 文件全路径
* 返回:文件的内容
*&#47.txt&))
while(raf.readLine())也就是 while(raf.readLine()==true)//就是还有内容就读
其他1条回答
为您推荐:
其他类似问题
java的相关知识
换一换
回答问题,赢新手礼包
个人、企业类
违法有害信息,请在下方选择后提交
色情、暴力
我们会通过消息、邮箱等方式尽快将举报结果通知您。怎样使用Java处理大文件_百度知道
怎样使用Java处理大文件
我有更好的答案
Charsets以下将从常规方法谈起.UTF_8);}这种方式开始时只占用很少的内存.nextLine();&#47,当文件足够大时很快就会导致程序抛出OutOfMemoryError 异常。例如!= null) {throw sc.nextLine();&#47:这意味这一过程大约耗费了2,这正是我们将要做的——通过行迭代,而不是把所有行都放在内存中。2、文件流FileInputStream inputStream =Scanner sc =try {inputStream = new FileInputStream(path):现在文件的所有行都被存储在内存中。把文件所有的内容都放在内存中很快会耗尽可用内存——不论实际可用内存有多大,然后做相应的处理,处理完之后把它扔掉。所以.1GB的内存——原因很简单;try {while (it.hasNext()) {String line = it:读取一个大约1G的文件;), &UTF-8&}由于整个文件不是全部存放在内存中..Files.readLines(new File(path):
@Testpublic void givenUsingGuava_whenIteratingAFile_thenWorks() throws IOException {String path = .; note that Scanner suppresses exceptionsif (sc.ioException() ;sc = new Scanner(inputStream, &quot:(大约消耗了0Mb内存)然而,当文件全部读到内存中后,我们最后可以看到(大约消耗了2GB内存);}if (sc != null) {sc.close();}}这种方案将会遍历文件中的所有行——允许对每一行进行处理,而不保持对它的引用。总之没有把它们存放在内存中:(大约消耗了150MB内存)3、Apache Commons IO流同样也可以使用Commons IO库实现,通过对比来说明应该如何使用java读取大文件。1、常规;/ System.out.println(line);}//}} finally {if (inputStream != null) {inputStream:在内存中读取读取文件行的标准方式是在内存中读取;/ do something with line}} finally {LineIterator.closeQuietly(it).UTF_8);FileUtils.readLines(new File(path));这种方法带来的问题是文件的所有行都被存放在内存中,我们只需要遍历文件的每一行.close(),利用该库提供的自定义LineIterator:LineIterator it = FileUtils.lineIterator(theFUTF-8&);while (sc.hasNextLine()) {String line = sc,这点是显而易见的。此外,我们通常不需要把文件的所有行一次性地放入内存中——相反, Charsets,Guava 和Apache Commons IO都提供了如下所示快速读取文件行的方法:Files.readLines(new File(path).ioException()
采纳率:96%
来自团队:
为您推荐:
其他类似问题
您可能关注的内容
换一换
回答问题,赢新手礼包
个人、企业类
违法有害信息,请在下方选择后提交
色情、暴力
我们会通过消息、邮箱等方式尽快将举报结果通知您。java 多线程按行读取txt 每个线程读的内容不能重复 求demo_百度知道
java 多线程按行读取txt 每个线程读的内容不能重复 求demo
求大神指点
public class Test{ public static void main(String args[])throws Exception{
File file = new File(&D:\\Test.java&);//Text文件
BufferedReader br = new BufferedReader(new FileReader(file));//构造一个BufferedReader类来读取文件
String s =
while((s = br.readLine())!=null){//使用readLine方法,一次读一行
System.out.println(s);
br.close();; }}
采纳率:98%
来自团队:
做法如下:private synchronized String readLine(InputStreamReader reader) throws Throwable {
return reader。这样,不管是你有 N 个线程,还是一个线程.readLine();}也就是说,你把原来程序中直接读的地方,改成调用上面的函数,由该函数统一读行,都不会发生读的行重复,或者读的行不完整的现象了其他内容我就不写了,我只写关键的部分,假设你是会从 InputStream 里面读行的了
private synchronized String read(BufferedReader reader) throws Throwable {
String str = &&;
while (reader.readLine() != null) {
str = reader.readLine();
}}我在run方法中调用这个方法的时候还是读的同一行
等等,我写个例子给你。
直接给你写了一个测试类,并发成图片了,你参考下内容的写法:
本回答被提问者采纳
notifyAll();data.txt&quot.start(););
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();+lineTXT);
} catch (IOException e) {
e.printStackTrace().println(Thread.currentThread()+&!= null) {
new Thread(new Runnable() {
public void run() {
String lineTXT =
InputStreamReader read = new InputStreamReader(new FileInputStream(
data), &UTF-8&
synchronized (bufferedReader) {
while ((lineTXT = bufferedReader.readLine()) .printStackTrace():&
final BufferedReader bufferedReader = new BufferedReader(read);
for (int i = 0;
} catch (InterruptedException e) {
bufferedReader.notify().
bufferedReader.wait();
bufferedReaderpublic static void main(String[] args) {
File data = new File(&quot
/** 9. * 读取TXE数据
10. */ public class f {
public static void main(String arg[]) {
String encoding = &GBK&; // 字符编码(可解决中文乱码问题 )
File file = new File(&c:/aa.txt&);
if (file.isFile() && file.exists()) {
InputStreamReader read = new InputStreamReader(
new FileInputStream(file), encoding);
BufferedReader bufferedReader = new BufferedReader(read);
String lineTXT =
while ((lineTXT = bufferedReader.readLine()) != null) {
System.out.println(lineTXT.toString().trim());
read.close();
System.out.println(&找不到指定的文件!&);
} catch (Exception e) {
System.out.println(&读取文件内容操作出错&);
e.printStackTrace();
这个是我才写的 我刚才测试了 可以运行 也可以读取 你试试看
希望我的回答对楼主有所帮助 谢谢
其他1条回答
为您推荐:
其他类似问题
线程的相关知识
换一换
回答问题,赢新手礼包
个人、企业类
违法有害信息,请在下方选择后提交
色情、暴力
我们会通过消息、邮箱等方式尽快将举报结果通知您。Java8读文件仅需一行代码
Java8读文件仅需一行代码JDK7中引入了新的文件操作类java nio file File,它包含了很多有用的方法来操作文件,比如检查文件是否为隐藏文件,或者是检查文件是否为只读文件。开发者还可以使用Files readAllBytes(
8读文件仅需一行代码JDK7中引入了新的文件操作类java.nio.file.File,它包含了很多有用的方法来操作文件,比如检查文件是否为隐藏文件,或者是检查文件是否为只读文件。开发者还可以使用Files.readAllBytes(Path)方法把整个文件读入内存,此方法返回一个字节数组,还可以把结果传递给String的构造器,以便创建字符串输出。此方法确保了当读入文件的所有字节内容时,文件属性是关闭的,否则就会出现IO异常或其它的未检查异常。这意味着在读文件到最后的块内容后,无需关闭文件。要注意,此方法不适合读取很大的文件,因为可能存在内存空间不足的问题。开发者还应该明确规定文件的字符编码,以避免任异常或解析错误。作者:chszs,转载需注明。博客主页:http://blog.csdn.net/chszs如果你想读入文件作为字符串,那么你还可以使用readAllLines(Path path, Charset cs)方法,此方法与之前的方法相似,也是在读完文件后无需关闭文件。但是它返回的不是字节数组,而是字符串数组。而且,Java8重写了此方法,无需指定字符集,直接使用UTF-8编码进行字符串转换。如果你想一行一行的读入文件作为字符串,那么你可以使用Files.lines()方法,它会从读入的文件中返回字符串流,并使用UTF-8编码把字节转换成字符。使用forEach()方法,可以只用一行Java代码实现把文件的所有内容输出到控制台,如下面第三个代码片段。import java.io.IOE
import java.nio.charset.StandardC
import java.nio.file.F
import java.nio.file.P
import java.util.L
public class FileReadingTest {
public static void main(String[] args) throws IOException {
// Java 7 例子
// Files.readAllBytes默认以UTF-8编码读入文件,故文件的编码如果不是UTF-8,那么中文内容会出现乱字符
System.out.println(new String(Files.readAllBytes(Paths.get("D:\\jd.txt"))));
// Java 8例子
List lines = Files.readAllLines(Paths.get("D:\\jd.txt"), StandardCharsets.UTF_8);
StringBuilder sb = new StringBuilder();
for(String line : lines){
sb.append(line);
String fromFile = sb.toString();
System.out.println(fromFile);
}如果使用的不是JDK7,而是JDK8,那么一行代码即可完成读文件。import static java.lang.System.
import static java.nio.file.Files.readAllB
import static java.nio.file.Paths.
import java.io.IOE
public class FileIntoString {
public static void main(String[] args) throws IOException {
// 一行代码搞定读文件,默认是UTF-8编码
out.println(new String(readAllBytes(get("d:/jd.txt"))));
}如果使用JDK8,那么还可以使用流API来读写文件,这样代码更简洁、高效。下面的例子中,lines()方法返回字符串流,字符串使用的是UTF-8编码。如下:import java.io.IOE
import java.nio.charset.StandardC
import java.nio.file.F
import java.nio.file.P
public class Java8FileReader {
public static void main(String[] args) throws IOException {
// Java8用流的方式读文件,更加高效
Files.lines(Paths.get("D:\\jd.txt"), StandardCharsets.UTF_8).forEach(System.out::println);
}上面的例子要注意几点:1)文件可能很大,可能会超出内存空间,使用前要做评估。2)要输出日志,记录为什么无法读取文件或者在文件时遇到的任何错误。3)在把字节转换成字符时,应该指定字符编码。4)要处理文件不存在的情况。还要注意,如果读入的文件的编码是ANSI编码,那么上面的例子在读取文件内容时会报java.nio.charset.MalformedInputException: Input length = 1错误。
红黑联盟&版权所有
Copyright&& 2017
All rights reserved.android按行读取文件内容的几个方法
投稿:junjie
字体:[ ] 类型:转载 时间:
这篇文章主要介绍了android按行读取文件内容的几个方法,java逐行读取文件内容的几个方法,需要的朋友可以参考下
一、简单版
&import java.io.FileInputS
void readFileOnLine(){
String strFileName = "Filename.txt";
FileInputStream fis = openFileInput(strFileName);
StringBuffer sBuffer = new StringBuffer();
DataInputStream dataIO = new DataInputStream(fis);
String strLine =
while((strLine =& dataIO.readLine()) != null) {
&&& sBuffer.append(strLine + “\n");
dataIO.close();
fis.close();
二、简洁版
//读取文本文件中的内容
&&& public static String ReadTxtFile(String strFilePath)
&&&&&&& String path = strFileP
&&&&&&& String content = ""; //文件内容字符串
&&&&&&&&&&& //打开文件
&&&&&&&&&&& File file = new File(path);
&&&&&&&&&&& //如果path是传递过来的参数,可以做一个非目录的判断
&&&&&&&&&&& if (file.isDirectory())
&&&&&&&&&&& {
&&&&&&&&&&&&&&& Log.d("TestFile", "The File doesn't not exist.");
&&&&&&&&&&& }
&&&&&&&&&&& else
&&&&&&&&&&& {
&&&&&&&&&&&&&&& try {
&&&&&&&&&&&&&&&&&&& InputStream instream = new FileInputStream(file);
&&&&&&&&&&&&&&&&&&& if (instream != null)
&&&&&&&&&&&&&&&&&&& {
&&&&&&&&&&&&&&&&&&&&&&& InputStreamReader inputreader = new InputStreamReader(instream);
&&&&&&&&&&&&&&&&&&&&&&& BufferedReader buffreader = new BufferedReader(inputreader);
&&&&&&&&&&&&&&&&&&&&&&& S
&&&&&&&&&&&&&&&&&&&&&&& //分行读取
&&&&&&&&&&&&&&&&&&&&&&& while (( line = buffreader.readLine()) != null) {
&&&&&&&&&&&&&&&&&&&&&&&&&&& content += line + "\n";
&&&&&&&&&&&&&&&&&&&&&&& }&&&&&&&&&&&&&&&
&&&&&&&&&&&&&&&&&&&&&&& instream.close();
&&&&&&&&&&&&&&&&&&& }
&&&&&&&&&&&&&&& }
&&&&&&&&&&&&&&& catch (java.io.FileNotFoundException e)
&&&&&&&&&&&&&&& {
&&&&&&&&&&&&&&&&&&& Log.d("TestFile", "The File doesn't not exist.");
&&&&&&&&&&&&&&& }
&&&&&&&&&&&&&&& catch (IOException e)
&&&&&&&&&&&&&&& {
&&&&&&&&&&&&&&&&&&&& Log.d("TestFile", e.getMessage());
&&&&&&&&&&&&&&& }
&&&&&&&&&&& }
&&&&&&&&&&&
三、用于长时间使用的apk,并且有规律性的数据
1,逐行读取文件内容
//首先定义一个数据类型,用于保存读取文件的内容
class WeightRecord {
&&&&&&& public WeightRecord(String timestamp, float weight) {
&&&&&&&&&&& this.timestamp =
&&&&&&&&&&& this.weight =
&&&&&&&&&&&
//开始读取
&private WeightRecord[] readLog() throws Exception {
&&&&&&& ArrayList&WeightRecord& result = new ArrayList&WeightRecord&();
&&&&&&& File root = Environment.getExternalStorageDirectory();
&&&&&&& if (root == null)
&&&&&&&&&&& throw new Exception("external storage dir not found");
&&&&&&& //首先找到文件
&&&&&&& File weightLogFile = new File(root,WeightService.LOGFILEPATH);
&&&&&&& if (!weightLogFile.exists())
&&&&&&&&&&& throw new Exception("logfile '"+weightLogFile+"' not found");
&&&&&&& if (!weightLogFile.canRead())
&&&&&&&&&&& throw new Exception("logfile '"+weightLogFile+"' not readable");
&&&&&&& long modtime = weightLogFile.lastModified();
&&&&&&& if (modtime == lastRecordFileModtime)
&&&&&&&&&&& return lastL
&&&&&&& // file exists, is readable, and is recently modified -- reread it.
&&&&&&& lastRecordFileModtime =
&&&&&&& // 然后将文件转化成字节流读取
&&&&&&& FileReader reader = new FileReader(weightLogFile);
&&&&&&& BufferedReader in = new BufferedReader(reader);
&&&&&&& long currentTime = -1;
&&&&&&& //逐行读取
&&&&&&& String line = in.readLine();
&&&&&&& while (line != null) {
&&&&&&&&&&& WeightRecord rec = parseLine(line);
&&&&&&&&&&& if (rec == null)
&&&&&&&&&&&&&&& Log.e(TAG, "could not parse line: '"+line+"'");
&&&&&&&&&&& else if (Long.parseLong(rec.timestamp) & currentTime)
&&&&&&&&&&&&&&& Log.e(TAG, "ignoring '"+line+"' since it's older than prev log line");
&&&&&&&&&&& else {
&&&&&&&&&&&&&&& Log.i(TAG,"line="+rec);
&&&&&&&&&&&&&&& result.add(rec);
&&&&&&&&&&&&&&& currentTime = Long.parseLong(rec.timestamp);
&&&&&&&&&&& }
&&&&&&&&&&& line = in.readLine();
&&&&&&& in.close();
&&&&&&& lastLog = (WeightRecord[]) result.toArray(new WeightRecord[result.size()]);
&&&&&&& return lastL
&&& //解析每一行
&&& private WeightRecord parseLine(String line) {
&&&&&&& if (line == null)
&&&&&&&&&&&
&&&&&&& String[] split = line.split("[;]");
&&&&&&& if (split.length & 2)
&&&&&&&&&&&
&&&&&&& if (split[0].equals("Date"))
&&&&&&&&&&&
&&&&&&& try {
&&&&&&&&&&& String timestamp =(split[0]);
&&&&&&&&&&& float weight =& Float.parseFloat(split[1]) ;
&&&&&&&&&&& return new WeightRecord(timestamp,weight);
&&&&&&& catch (Exception e) {
&&&&&&&&&&& Log.e(TAG,"Invalid format in line '"+line+"'");
&&&&&&&&&&&
2,保存为文件
public boolean logWeight(Intent batteryChangeIntent) {
&&&&&&&&&&& Log.i(TAG, "logBattery");
&&&&&&&&&&& if (batteryChangeIntent == null)
&&&&&&&&&&&&&&&
&&&&&&&&&&& try {
&&&&&&&&&&&&&&& FileWriter out =
&&&&&&&&&&&&&&& if (mWeightLogFile != null) {
&&&&&&&&&&&&&&&&&&& try {
&&&&&&&&&&&&&&&&&&&&&&& out = new FileWriter(mWeightLogFile, true);
&&&&&&&&&&&&&&&&&&& }
&&&&&&&&&&&&&&&&&&& catch (Exception e) {}
&&&&&&&&&&&&&&& }
&&&&&&&&&&&&&&& if (out == null) {
&&&&&&&&&&&&&&&&&&& File root = Environment.getExternalStorageDirectory();
&&&&&&&&&&&&&&&&&&& if (root == null)
&&&&&&&&&&&&&&&&&&&&&&& throw new Exception("external storage dir not found");
&&&&&&&&&&&&&&&&&&& mWeightLogFile = new File(root,WeightService.LOGFILEPATH);
&&&&&&&&&&&&&&&&&&& boolean fileExists = mWeightLogFile.exists();
&&&&&&&&&&&&&&&&&&& if (!fileExists) {
&&&&&&&&&&&&&&&&&&&&&&& if(!mWeightLogFile.getParentFile().mkdirs()){
&&&&&&&&&&&&&&&&&&&&&&&&&&& Toast.makeText(this, "create file failed", Toast.LENGTH_SHORT).show();
&&&&&&&&&&&&&&&&&&&&&&& }
&&&&&&&&&&&&&&&&&&&&&&& mWeightLogFile.createNewFile();
&&&&&&&&&&&&&&&&&&& }
&&&&&&&&&&&&&&&&&&& if (!mWeightLogFile.exists()) {
&&&&&&&&&&&&&&&&&&&&&&& Log.i(TAG, "out = null");
&&&&&&&&&&&&&&&&&&&&&&& throw new Exception("creation of file '"+mWeightLogFile.toString()+"' failed");
&&&&&&&&&&&&&&&&&&& }
&&&&&&&&&&&&&&&&&&& if (!mWeightLogFile.canWrite())
&&&&&&&&&&&&&&&&&&&&&&& throw new Exception("file '"+mWeightLogFile.toString()+"' is not writable");
&&&&&&&&&&&&&&&&&&& out = new FileWriter(mWeightLogFile, true);
&&&&&&&&&&&&&&&&&&& if (!fileExists) {
&&&&&&&&&&&&&&&&&&&&&&& String header = createHeadLine();
&&&&&&&&&&&&&&&&&&&&&&& out.write(header);
&&&&&&&&&&&&&&&&&&&&&&& out.write('\n');
&&&&&&&&&&&&&&&&&&& }
&&&&&&&&&&&&&&& }
&&&&&&&&&&&&&&& Log.i(TAG, "out != null");
&&&&&&&&&&&&&&& String extras = createBatteryInfoLine(batteryChangeIntent);
&&&&&&&&&&&&&&& out.write(extras);
&&&&&&&&&&&&&&& out.write('\n');
&&&&&&&&&&&&&&& out.flush();
&&&&&&&&&&&&&&& out.close();
&&&&&&&&&&&&&&&
&&&&&&&&&&& } catch (Exception e) {
&&&&&&&&&&&&&&& Log.e(TAG,e.getMessage(),e);
&&&&&&&&&&&&&&&
&&&&&&&&&&& }
您可能感兴趣的文章:
大家感兴趣的内容
12345678910
最近更新的内容
常用在线小工具

我要回帖

更多关于 shell 按行读取文件 的文章

 

随机推荐