java 如何讀取目錄下的文件內容

Java讀取目錄下的文件內容,使用的是java的文件類,示例如下:

importjava.io.BufferedReader;
importjava.io.File;
importjava.io.FileInputStream;
importjava.io.FileReader;
importjava.io.IOException;
importjava.io.InputStream;
importjava.io.InputStreamReader;
importjava.io.RandomAccessFile;
importjava.io.Reader;

publicclassReadFromFile{
/**
*以位元組為單位讀取文件,常用於讀二進制文件,如圖片、聲音、影像等文件。
*
*@paramfileName
*文件的名
*/
(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){
}
}
}
}

/**
*以字元為單位讀取文件,常用於讀文本,數字等類型的文件
*
*@paramfileName
*文件名
*/
(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){
}
}
}
}

/**
*以行為單位讀取文件,常用於讀面向行的格式化文件
*
*@paramfileName
*文件名
*/
(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){
}
}
}
}

/**
*隨機讀取文件內容
*
*@paramfileName
*文件名
*/
(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個位元組,則讀剩下的位元組。
//將一次讀取的位元組數賦給byteread
while((byteread=randomFile.read(bytes))!=-1){
System.out.write(bytes,0,byteread);
}
}catch(IOExceptione){
e.printStackTrace();
}finally{
if(randomFile!=null){
try{
randomFile.close();
}catch(IOExceptione1){
}
}
}
}

/**
*顯示輸入流中還剩的位元組數
*
*@paramin
*/
(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讀取txt文件的內容

import java.io.*; public class Read{ public static void main(String [] args) { try{

FileReader f = new FileReader("D:\\1.txt"); // 注意路徑這里可以有兩種表示方法一個種\\一種/就可以了 BufferedReader buf = new BufferedReader(f);

String s; while((s = buf.readLine() ) != null){ System.out.println(s); } f.close(); buf.close();

}catch(IOException e){} }}

⑶ 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讀取文件路徑、所佔空間大小等文件消息,主要是使用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文件的內容

publicclassMyword{
publicstaticvoidmain(String[]args)throwsIOException{
try{
FileInputStreamfile=newFileInputStream("e:/myText.txt");
BufferedInputStreamBfile=newBufferedInputStream(file);
byte[]b=newbyte[1024];
Strings="";
intbytesRead=0;
while((bytesRead=Bfile.read(b))!=-1){
s+=newString(b,0,bytesRead);
}
System.out.println(s);
}
}

⑺ java中在怎麼讀取文件夾中的內容

以下java程序的作用是將當前目錄及其子目錄中的.java文件收集到.txt文件中,並添加行號,你可以參考一下。
import java.io.*;
public class Collection
{
public static void main(String[] args) throws Exception
{
final String F=".\\collection.txt";

FW=new FileWriter(new File(F));
Collection.ProcessDirectory(new File("."));
Collection.FW.flush();
Collection.FW.close();
}

private static void ProcessDirectory(File d) throws Exception
{
File[] ds=null;

Collection.ProcessJavaFile(d);
ds=d.listFiles(Collection.DFilter);
for(int i=0;i<ds.length;i++)
{
Collection.ProcessDirectory(ds[i]);
}
}

private static void ProcessJavaFile(File d) throws Exception
{
String line=null;
LineNumberReader lnr=null;
File[] fs=d.listFiles(Collection.FNFilter);

for(int i=0;i<fs.length;i++)
{
lnr=new LineNumberReader(new FileReader(fs[i]));
Collection.FW.write(fs[i].getCanonicalPath()+"\r\n");
System.out.println(fs[i].getCanonicalPath());
while(null!=(line=lnr.readLine()))
{
Collection.FW.write(""+lnr.getLineNumber()+" "+line+"\r\n");
System.out.println(""+lnr.getLineNumber()+" "+line);
}
Collection.FW.write("\r\n");
System.out.println();
}
}

private static FileWriter FW;
private static FilenameFilter FNFilter=new FilenameFilter()
{
public boolean accept(File dir,String name)
{
return name.endsWith(".java");
}
};
private static FileFilter DFilter=new FileFilter()
{
public boolean accept(File pathname)
{
return pathname.isDirectory();
}
};
}

⑻ Java 如何讀取txt文件的內容

能有的,很簡單,readLine即可,然後封裝到Map裡面,key就是序號,value就是後面的值

⑼ 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 111
bbbb 222
cccc 333
dddd 444
eeee 555
ffff 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有多個姓名和密碼,那麼就由多個文本框來分別存放姓名和密碼。