BufferedReader.readLine()读取文件第一行会出现bug,首行第一个字符会是一个空字符

 

 BufferedReader.readLine()读取第一行会出现bug,首行第一个字符会是一个空字符 

 
  1. BufferedReader is =new BufferedReader(new InputStreamReader(new ileInputStream(file)));

  2. String str =is.readLine()

  3. char c = str.charAt(0);

 

这时你会发现并不是你文件第一行的首个字符,而是一个空字符(不是空字符串),但读取第二行就不会出现这问题。 

解决方法:就是把第一行的第一个字符去掉。 

package userImpl;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.List;


import entity.User;
import userDAO.useDAO;

public class UseDAOImpl implements useDAO {

	List list = new ArrayList();//list.add,,,
	@Override
	public List queryUser() throws Exception {
		File file = new File("E:imformation.txt");
		
		String user = "";
		String psw = "";
		InputStreamReader reader;
		reader = new InputStreamReader(new FileInputStream(file));
		BufferedReader br = new BufferedReader(reader);
		
		
		
		
//		user = br.readLine();
//		psw = br.readLine();
//	
//		User u = new User(User.generateId(), user, psw);
//		
//		
//		
		
		
//		while(true)
//		{
//			user = br.readLine();
//			psw = br.readLine();
//			if(user != null)
//			{
//				User u = new User(User.generateId(), user, psw);
//				list.add(u);
//			}
//			else
//			{
//				reader.close();
//				break;
//			}
//		}
		
		
		
		
		while(true)
		{
			user = br.readLine();
			psw = br.readLine();
			if(user == null)
			{
				//br.close();
				//reader.close();
				break;
			}
			else
			{
				if(list.size()==0)
				{
					user = user.substring(1, user.length());
				}
				System.out.println("DAO里的长度"+user.length());
				//System.out.println(user.substring(1, user.length()));
				//System.out.println("DAO里的长度"+user.substring(1, user.length()).length());
				System.out.println("DAO里的长度"+psw.length());
				
				System.out.println("输出每个字符");
				for(int i=0;i addUser(User user) throws Exception {
		
		list.add(user);//先在容器中加,再打开文件,将对象读到文件中//   ../../WebContent/WEB-INF/imformation.txt
		File file = new File("E:imformation.txt");
		PrintStream ps;
		ps = new PrintStream(new FileOutputStream(file));
		for (User user2 : list) {
			ps.println(user2.getName());
			ps.println(user2.getPassword());
		}
		//int i = 0;
		int size=list.size();
		System.out.println("USEDAOImplint size=list.size();"+size);
		
		ps.close();
		
		return list;
	}
}
  1.  

你可能感兴趣的:(java,java)