java获取文件内容|java如何读取一个txt文件的所有内容

java获取文件内容|java如何读取一个txt文件的所有内容的第1张示图

『壹』 如何用java读取一个txt 文件内的内容并把它

import java.io.BufferedInputStream;import java.io.BufferedReader;import java.io.File;import java.io.FileInputStream;import java.io.InputStreamReader;import java.io.Reader;public class H {/*** 功能:Java读取txt文件的内容* 步骤:1:先获得文件句柄* 2:获得文件句柄当做是输入一个字节码流,需要对这个输入流进行读取* 3:读取到输入流后,需要读取生成字节流* 4:一行一行的输出。readline()。* 备注:需要考虑的是异常情况* @param filePath*/public static void readTxtFile(String filePath){try {String encoding="GBK";File file=new File(filePath);if(file.isFile() && file.exists()){ //判断文件是否存在InputStreamReader read = new InputStreamReader(new FileInputStream(file),encoding);//考虑到编码格式BufferedReader bufferedReader = new BufferedReader(read);String lineTxt = null;while((lineTxt = bufferedReader.readLine()) != null){System.out.println(lineTxt);}read.close();}else{System.out.println("找不到指定的文件");}} catch (Exception e) {System.out.println("读取文件内容出错");e.printStackTrace();}}public static void main(String argv[]){String filePath = "L:\\20121012.txt";// "res/";readTxtFile(filePath);}}

『贰』 java读取指定目录下的文件内容

publicclassReadFromFile{/***以字节为单位读取文件,常用于读二进制文件,如图片、声音、影像等文件。*/(StringfileName){Filefile=newFile(fileName);InputStreamin=null;try{System.out.println("以字节为单位读取文件内容,一次读一个字节:");//一次读一个字节in=newFileInputStream(file);inttempbyte;while((tempbyte=in.read())!=-1){System.out.write(tempbyte);}in.close();}catch(IOExceptione){e.printStackTrace();return;}try{System.out.println("以字节为单位读取文件内容,一次读多个字节:");//一次读多个字节byte[]tempbytes=newbyte[100];intbyteread=0;in=newFileInputStream(fileName);ReadFromFile.showAvailableBytes(in);//读入多个字节到字节数组中,byteread为一次读入的字节数while((byteread=in.read(tempbytes))!=-1){System.out.write(tempbytes,0,byteread);}}catch(Exceptione1){e1.printStackTrace();}finally{if(in!=null){try{in.close();}catch(IOExceptione1){}}}}/***以字符为单位读取文件,常用于读文本,数字等类型的文件*/(StringfileName){Filefile=newFile(fileName);Readerreader=null;try{System.out.println("以字符为单位读取文件内容,一次读一个字节:");//一次读一个字符reader=newInputStreamReader(newFileInputStream(file));inttempchar;while((tempchar=reader.read())!=-1){//对于windows下,这两个字符在一起时,表示一个换行。//但如果这两个字符分开显示时,会换两次行。//因此,屏蔽掉,或者屏蔽。否则,将会多出很多空行。if(((char)tempchar)!=''){System.out.print((char)tempchar);}}reader.close();}catch(Exceptione){e.printStackTrace();}try{System.out.println("以字符为单位读取文件内容,一次读多个字节:");//一次读多个字符char[]tempchars=newchar[30];intcharread=0;reader=newInputStreamReader(newFileInputStream(fileName));//读入多个字符到字符数组中,charread为一次读取字符数while((charread=reader.read(tempchars))!=-1){//同样屏蔽掉不显示if((charread==tempchars.length)&&(tempchars[tempchars.length-1]!='')){System.out.print(tempchars);}else{for(inti=0;i<charread;i++){if(tempchars[i]==''){continue;}else{System.out.print(tempchars[i]);}}}}}catch(Exceptione1){e1.printStackTrace();}finally{if(reader!=null){try{reader.close();}catch(IOExceptione1){}}}}/***以行为单位读取文件,常用于读面向行的格式化文件*/(StringfileName){Filefile=newFile(fileName);BufferedReaderreader=null;try{System.out.println("以行为单位读取文件内容,一次读一整行:");reader=newBufferedReader(newFileReader(file));StringtempString=null;intline=1;//一次读入一行,直到读入null为文件结束while((tempString=reader.readLine())!=null){//显示行号System.out.println("line"+line+":"+tempString);line++;}reader.close();}catch(IOExceptione){e.printStackTrace();}finally{if(reader!=null){try{reader.close();}catch(IOExceptione1){}}}}/***随机读取文件内容*/(StringfileName){RandomAccessFilerandomFile=null;try{System.out.println("随机读取一段文件内容:");//打开一个随机访问文件流,按只读方式randomFile=newRandomAccessFile(fileName,"r");//文件长度,字节数longfileLength=randomFile.length();//读文件的起始位置intbeginIndex=(fileLength>4)?4:0;//将读文件的开始位置移到beginIndex位置。randomFile.seek(beginIndex);byte[]bytes=newbyte[10];intbyteread=0;//一次读10个字节,如果文件内容不足10个字节,则读剩下的字节。//将一次读取的字节数赋给bytereadwhile((byteread=randomFile.read(bytes))!=-1){System.out.write(bytes,0,byteread);}}catch(IOExceptione){e.printStackTrace();}finally{if(randomFile!=null){try{randomFile.close();}catch(IOExceptione1){}}}}/***显示输入流中还剩的字节数*/(InputStreamin){try{System.out.println("当前字节输入流中的字节数为:"+in.available());}catch(IOExceptione){e.printStackTrace();}}publicstaticvoidmain(String[]args){StringfileName="C:/temp/newTemp.txt";ReadFromFile.readFileByBytes(fileName);ReadFromFile.readFileByChars(fileName);ReadFromFile.readFileByLines(fileName);ReadFromFile.readFileByRandomAccess(fileName);}}

『叁』 java中怎么读取文件内容和删除文件

/***读取文本文件的内容到一个向量中**@是绝对路径文件*@returnVector,每一个元素是文件的一行*/(StringstrFileName)throwsFileNotFoundException,IOException{Vectorcontent=newVector();FileReaderobjFile=newFileReader(strFileName);BufferedReaderobjBuffer=newBufferedReader(objFile);StringstrLine=objBuffer.readLine();while(strLine!=null){content.add(strLine);strLine=objBuffer.readLine();}objBuffer.close();objFile.close();returncontent;}/***删除文件夹下所有内容,包括此文件夹*/publicstaticbooleandelAll(FileobjFile)throwsIOException{//文件夹不存在不存在if(!objFile.exists()){//log.error("指定目录不存在:"+objFile.getName());returnfalse;}//保存中间结果booleanrslt=true;if(!(rslt=objFile.delete())){//先尝试直接删除//若文件夹非空。枚举、递归删除里面内容Filesubs[]=objFile.listFiles();for(inti=0;i<=subs.length-1;i++){if(subs[i].isDirectory())delAll(subs[i]);//递归删除子文件夹内容rslt=subs[i].delete();//删除子文件夹本身}rslt=objFile.delete();//删除此文件夹本身}if(!rslt){//log.error("无法删除:"+objFile.getName());returnfalse;}returntrue;}

『肆』 JAVA读取文件内容的问题

import java.io.BufferedReader;import java.io.File;import java.io.FileNotFoundException;import java.io.FileReader;import java.io.IOException;public class test { public static void main(String[] args) { File file = new File("D:/1.txt"); try { FileReader fr = new FileReader(file); BufferedReader br = new BufferedReader(fr); String Ls; System.out.println("读取中,文件的内容如下:"); while(( Ls = br.readLine())!=null){ System.out.println(Ls); //Ls = br.readLine(); 此句去掉 } br.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }}楼主要去掉while里面的Ls = br.readLine(); 这句,每次调用readline后指针会指向下一行

『伍』 JAVA怎样来获取上传的txt文件里面的内容

用两个页面来完成你的功能。index.jsp接受你上传的文件;uploadfile.jsp显示上传文件中的内容。具体要显示什么,你根据自己需要修改下吧。index.jsp的内容如下:<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%><html> <head> <title>index</title> </head> <body> <center> <form action="uploadfile.jsp" method = "post"> newFile: <input type = "file" name = "newFile" size=60 value=""/><br> <input type = "submit" value = "upload"> </form> </center> </body></html>———————————-uploadfile.jsp内容如下:<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%><%@ page import = "java.io.*" %><form action = "uploadfile.jsp" method = "post"> <table border = "1"> <tr> <th>ID</th> <th>UserName</th> <th>Password</th> </tr> <% try{ String s = request.getParameter("newFile"); String ss = new String(s.getBytes("ISO-8859-1"),"UTF-8"); File f = new File(ss); FileReader fr = new FileReader(f); BufferedReader br = new BufferedReader(fr); String str = ""; int i = 1; while((str = br.readLine()) != null){ ArrayList list = new ArrayList(); StringTokenizer st = new StringTokenizer(str, " "); while(st.hasMoreElements()){ list.add((String)st.nextElement()); } String u = (String)list.get(0); String p = (String)list.get(1) ; %> <tr> <td><%=i %></td> <td><input type = "text" name = "u" value="<%=u %>"/></td> <td><input type = "text" name = "p" value="<%=p %>"/></td> </tr> <% i++; } br.close(); }catch(Exception e){ out.print(e); } %> </table> </form>其实这种方式不是最理想的上传形式,不过要实现通用的那种方式的话,还需要下载一个jspSmartUpload组件来实现,这种方式是非常简洁的。如果你要上传的txt文件的内容为:aaa 111bbbb 222cccc 333dddd 444eeee 555ffff 666那么当你运行这个程序后,你在uploadfile.jsp页面上看到的输出结果是:ID UserName Password 1 aaa 111 2 bbbb 222 3 cccc 333 4 dddd 444 5 eeee 555 6 ffff 666 现在这样的结果是你要的吗?已经修改了,应该达到了你的目的了吧,不过了结果是在一个jsp页面中输出的。姓名和密码分别放在两个不同的文本框中,如果txt有多个姓名和密码,那么就由多个文本框来分别存放姓名和密码。

『陆』 java文件读取指定内容

给你写了一个小方法,应该满足你的要求了://url是你要读取的文件的路径,是所要求的包含的字符串如这里是“COMMON.9006 – 000332”。public static void readWantedText(String url, String wanted) { try { FileReader fr = new FileReader(url); BufferedReader br = new BufferedReader(fr); String temp = "";// 用于临时保存每次读取的内容 while (temp != null) { temp = br.readLine(); if (temp != null && temp.contains(wanted)) { System.out.println(temp); } } } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } }用的话直接调用这个方法就可以了:例如readWantedText("D:\\test.txt", "COMMON.9006 – 000332");//注意java路径需要在每条\前面在加条\表示转义。

『柒』 java中怎样从一个文件中读取文件信息

java读取文件路径、所占空间大小等文件消息,主要是使用FileInputStream类来操作,示例如内下:

importjava.io.File;importjava.io.FileInputStream;publicclassceshi{publicstaticvoidmain(String[]args)throwsException{容java.io.FilelocalFile=newFile("D:\1.txt");FileInputStreamins=newFileInputStream(localFile);intcountLen=ins.available();byte[]m_binArray=newbyte[countLen];ins.read(m_binArray);ins.close();System.out.println(localFile.getAbsoluteFile()+""+localFile.getFreeSpace());}}

运行结果如下:

『捌』 java如何读取txt文件内容

给你两个方法,你可以看看;//获取值返回String文本publicStringtxt2String(StringfilePath){Filefile=newFile(filePath);StringBuilderresult=newStringBuilder();try{BufferedReaderbr=newBufferedReader(newFileReader(file));//构造一个BufferedReader类来读取文件Strings=null;while((s=br.readLine())!=null){//使用readLine方法,一次读一行result.append(s+System.lineSeparator());}br.close();}catch(Exceptione){e.printStackTrace();}returnresult.toString();}//获取值不返回String文本publicvoidreadTxtFile(StringfilePath){try{Stringencoding="GBK";Filefile=newFile(filePath);if(file.isFile()&&file.exists()){//判断文件是否存在InputStreamReaderread=newInputStreamReader(newFileInputStream(file),encoding);//考虑到编码格式BufferedReaderbufferedReader=newBufferedReader(read);StringlineTxt=null;while((lineTxt=bufferedReader.readLine())!=null){System.out.println(lineTxt);}read.close();}else{System.out.println("找不到指定的文件");}}catch(Exceptione){System.out.println("读取文件内容出错");e.printStackTrace();}}

『玖』 java如何获取文件信息

File 类是对文件和文件夹的抽象,包含了对文件和文件夹的多种属性和操作方法。File类的常用方法如下表:返回方法说明String getName 获取文件名称 String getParent 获取文件的父路径字符串 String getPath 获取文件的相对路径字符串 String getAbsolutePath 获取文件的绝对路径字符串 boolean exists 判断文件或者文件夹是否存在 boolean isFile 判断是不是文件类型 boolean isDirectory 判断是不是文件夹类型 boolean delete 删除文件或文件夹,如果删除成功返回结果为true boolean mkdir 创建文件夹,创建成功返回true boolean setReadOnly 设置文件或文件夹的只读属性 long length 获取文件的长度 long lastModified 获取文件的最后修改时间 String[ ] list 获取文件夹中的文件和子文件夹的名称,并存放到字符串数组中

『拾』 java如何读取一个txt文件的所有内容

import java.io.BufferedReader;import java.io.File;import java.io.FileReader;import java.io.IOException;public class ReadFile { public static void main(String[] args) throws IOException { String fileContent = readFileContent(""); System.out.println(fileContent); } //参数string为你的文件名 private static String readFileContent(String fileName) throws IOException { File file = new File(fileName); BufferedReader bf = new BufferedReader(new FileReader(file)); String content = ""; StringBuilder sb = new StringBuilder(); while(content != null){ content = bf.readLine(); if(content == null){ break; } sb.append(content.trim()); } bf.close(); return sb.toString(); }}求采纳为满意回答。

未经允许不得转载:山九号 » java获取文件内容|java如何读取一个txt文件的所有内容

赞 (0)