導航:首頁 > 編程語言 > java讀文件字元串

java讀文件字元串

發布時間:2022-04-20 23:26:33

java怎樣把一個文本內容讀取成字元串

java中可以使用Scanner來讀取文件的內容,首先先通過File創建一個文件,再通過Scanner的nextLine()方法讀取文本的內容。
具體代碼如下所示:
public class Demo {
public static void main(String[] args) {
File file = new File("C:/Users/hp/Desktop/data.txt");
Scanner scanner = null;
try {
scanner = new Scanner(file);
String str = null;
while (scanner.hasNextLine()) {
str += scanner.nextLine() + "\r\n";
}
System.out.println(str);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (scanner != null) {
scanner.close();
}
}
}
}
Scanner的主要功能是簡化文本掃描,這個類最實用的地方表現在獲取控制台輸入。

⑵ JAVA中幾種讀取文件字元串的效率哪個比較高

方式一

/**
* 以位元組為單位讀取文件,常用於讀二進制文件,如圖片、聲音、影像等文件。
* 當然也是可以讀字元串的。
*/
/* 貌似是說網路環境中比較復雜,每次傳過來的字元是定長的,用這種方式?*/
public String readString1()
{
try
{
//FileInputStream 用於讀取諸如圖像數據之類的原始位元組流。要讀取字元流,請考慮使用 FileReader。
FileInputStream inStream=this.openFileInput(FILE_NAME);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
byte[] buffer=new byte[1024];
int length=-1;
while( (length = inStream.read(buffer) != -1)
{
bos.write(buffer,0,length);
// .write方法 SDK 的解釋是 Writes count bytes from the byte array buffer starting at offset index to this stream.
// 當流關閉以後內容依然存在
}
bos.close();
inStream.close();
return bos.toString();
// 為什麼不一次性把buffer得大小取出來呢?為什麼還要寫入到bos中呢? return new(buffer,"UTF-8") 不更好么?
// return new String(bos.toByteArray(),"UTF-8");
}
}

方式二

// 有人說了 FileReader 讀字元串更好,那麼就用FileReader吧
// 每次讀一個是不是效率有點低了?
private static String readString2()
{
StringBuffer str=new StringBuffer("");
File file=new File(FILE_IN);
try {
FileReader fr=new FileReader(file);
int ch = 0;
while((ch = fr.read())!=-1 )
{
System.out.print((char)ch+" ");
}
fr.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.out.println("File reader出錯");
}
return str.toString();
}

方式三

/*按位元組讀取字元串*/
/* 個人感覺最好的方式,(一次讀完)讀位元組就讀位元組吧,讀完轉碼一次不就好了*/
private static String readString3()
{
String str="";
File file=new File(FILE_IN);
try {
FileInputStream in=new FileInputStream(file);
// size 為字串的長度 ,這里一次性讀完
int size=in.available();
byte[] buffer=new byte[size];
in.read(buffer);
in.close();
str=new String(buffer,"GB2312");
} catch (IOException e) {
// TODO Auto-generated catch block
return null;
e.printStackTrace();
}
return str;
}

/*InputStreamReader+BufferedReader讀取字元串 , InputStreamReader類是從位元組流到字元流的橋梁*/
/* 按行讀對於要處理的格式化數據是一種讀取的好方式 */
private static String readString4()
{
int len=0;
StringBuffer str=new StringBuffer("");
File file=new File(FILE_IN);
try {
FileInputStream is=new FileInputStream(file);
InputStreamReader isr= new InputStreamReader(is);
BufferedReader in= new BufferedReader(isr);
String line=null;
while( (line=in.readLine())!=null )
{
if(len != 0) // 處理換行符的問題
{
str.append("\r\n"+line);
}
else
{
str.append(line);
}
len++;
}
in.close();
is.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return str.toString();
}

⑶ java中如何像readLine()讀取文件一樣讀取字元串

最簡單的辦法 就是用ByteArrayInputStream

比如

Stringa="aaaaa";
ByteArrayInputStreamis=newByteArrayInputStream(a.getBytes());
BufferedReaderbr=newBufferedReader(newInputStreamReader(is));
br.readLine()

當然自己實現一下按行讀取也挺方便的。用a.getBytes()獲取字元串的字元數組,然後按順序去讀里邊的每個字元,檢查是否是回車或換行符 不是就用stringbuffer.append把字元加入stringbuffer,是就用stringbuffer.toString返回字元串就行。

⑷ java 怎麼讀取文件中的字元和數據

package test;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

class Test {

private static BufferedReader bw;

public static void main(String[] args) {
String ss = null;
List<TestPo> list = new ArrayList<TestPo>();
try{
File file=new File("E:\\test.txt");
FileOutputStream out=new FileOutputStream(new File("E:\\test1.txt"),true);
bw=new BufferedReader(new FileReader(file));
boolean flag = true;
int[] temps = null;
while((ss=bw.readLine())!=null){

String[] mark = ss.split(":");
int sum =0;
TestPo po = new TestPo();
int[] temp = new int[mark.length-1];
temps = new int[mark.length-1];
for (int i = 1;i< mark.length;i++) {
temp[i-1] = Integer.parseInt(mark[i].trim());
sum += temp[i-1];
if (flag) {
temps[i-1] = 0;
}
}
flag = false;
po.setMark(temp);
po.setName(mark[0]);
po.setAvg(sum/(mark.length-1));
list.add(po);
out.write(("\t\n"+ss).getBytes());
}

bw.close();
out.close();

int row = list.size();
int[][] marks = new int[row+1][];
for (int i = 0; i < row; i++) {
marks[i] = list.get(i).getMark();
}
marks[row] = temps;
int sumTemp =0 ;
int count = list.get(0).getMark().length;
for (int i = 0; i < count; i++) {
for (int j = 0; j < row; j++) {
sumTemp += marks[j][i];
}
marks[row][i] = sumTemp/row;
sumTemp = 0;
}
for (int[] is : marks) {
for (int i : is) {
System.out.print(i+" ");
}
System.out.println();
}

}catch(IOException e){
e.printStackTrace();
}

for (TestPo po : list) {
System.out.println("Name:"+po.getName()+" AVG:"+po.getAvg());
}
}

}

class TestPo{

private String name;
private Integer avg;
private int[] mark;

public int[] getMark() {
return mark;
}
public void setMark(int[] mark) {
this.mark = mark;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAvg() {
return avg;
}
public void setAvg(Integer avg) {
this.avg = avg;
}

}

⑸ Java如何將文本文檔中的字元串讀取到字元串數組

使用RandomAccessFile先讀取一次計算行數,seek重置到文件頭部,再讀取每行,賦值給a數組。

importjava.io.FileNotFoundException;
importjava.io.IOException;
importjava.io.RandomAccessFile;
publicclassTest{
//此題目關鍵是根據文件內容確定二維數組的行數和列數
publicstaticvoidmain(String[]args){
RandomAccessFilereader=null;
try{
reader=newRandomAccessFile("test.txt","r");
intn=0;//行數
while(reader.readLine()!=null){//第一次按行讀取只為了計算行數
n++;
}
String[][]a=newString[n][];
reader.seek(0);//重置到文件頭部
intj;
Stringline;
String[]strs;
inti=0;
while((line=reader.readLine())!=null){//第二次按行讀取是真正的讀取數據
strs=line.split("");//把讀取到的一行數據以空格分割成子字元串數組
a[i]=newString[strs.length];//列數就是數組strs的大小,此句是逐行創建二維數組的列
for(j=0;j<strs.length;j++){
a[i][j]=strs[j];//逐行給二維數組的每一列賦值
}
i++;
}
for(i=0;i<n;i++){
for(j=0;j<a[i].length;j++){
System.out.println("a["+i+"]["+j+"]="+a[i][j]);
}
}
}catch(FileNotFoundExceptione){
e.printStackTrace();
}catch(IOExceptione){
e.printStackTrace();
}finally{
if(reader!=null){
try{
reader.close();
reader=null;
}catch(IOExceptione){
e.printStackTrace();
}
}
}
}
}

運行結果如圖

⑹ 怎麼用java來讀取TXT文件中的字元串

java中所有數據的傳輸都是通過位元組流的形式,包括文件或圖片。 那麼當你要讀取一個文件時,首先將文件的絕對路徑告訴java,調用對應的api就可以拿到該文件的位元組流,下面是一段讀取xml文件的例子 SAXReader reader = new SAXReader(); Document

⑺ 用java 讀文件,如何從某一字元串開始讀

//前面做一個讀取文件的scanner

result = false;
while (!result)//這里主要是找到@data,使scanner的游標跳到@data之後
{
String s = scan.nextLine();

if (s.equals("@data")

result = true;

}

//讀取剩下的文檔,並寫入另外一個文件

⑻ java中怎樣將文件的內容讀取成字元串

java中有四種將文件的內容讀取成字元串

方式一:

Java code

/**

*以位元組為單位讀取文件,常用於讀二進制文件,如圖片、聲音、影像等文件。

*當然也是可以讀字元串的。

*/

/*貌似是說網路環境中比較復雜,每次傳過來的字元是定長的,用這種方式?*/

publicStringreadString1()

{

try

{

//FileInputStream用於讀取諸如圖像數據之類的原始位元組流。要讀取字元流,請考慮使用FileReader。

FileInputStreaminStream=this.openFileInput(FILE_NAME);

ByteArrayOutputStreambos=newByteArrayOutputStream();

byte[]buffer=newbyte[1024];

intlength=-1;

while((length=inStream.read(buffer)!=-1)

{

bos.write(buffer,0,length);

//.write方法SDK的解釋是m.

//當流關閉以後內容依然存在

}

bos.close();

inStream.close();

returnbos.toString();

//為什麼不一次性把buffer得大小取出來呢?為什麼還要寫入到bos中呢?returnnew(buffer,"UTF-8")不更好么?

//returnnewString(bos.toByteArray(),"UTF-8");

}

}

方式二:

Java code

方式四:

Java code

/*InputStreamReader+BufferedReader讀取字元串,InputStreamReader類是從位元組流到字元流的橋梁*/

/*按行讀對於要處理的格式化數據是一種讀取的好方式*/

()

{

intlen=0;

StringBufferstr=newStringBuffer("");

Filefile=newFile(FILE_IN);

try{

FileInputStreamis=newFileInputStream(file);

InputStreamReaderisr=newInputStreamReader(is);

BufferedReaderin=newBufferedReader(isr);

Stringline=null;

while((line=in.readLine())!=null)

{

if(len!=0)//處理換行符的問題

{

str.append(" "+line);

}

else

{

str.append(line);

}

len++;

}

in.close();

is.close();

}catch(IOExceptione){

//TODOAuto-generatedcatchblock

e.printStackTrace();

}

returnstr.toString();

}

⑼ java怎麼從一個文件讀取字元串,再存到一個字元串數組里

首先,可以直接寫入string的,這段程序的這種寫法很無聊,讓你誤解了。
如: out.write(p_send_text);

其次,如果想寫入一行並且換行的話,那麼得包裝一個printwriter,如:
PrintWriter out = new PrintWriter(FileWriter(file, true));
out.println(p_send_text);

在Java里,
char表示一個字元,它可以直接轉換為int, byte, long.(ascii/unicode碼)
String表示一串字元,它可以通過某些方法轉換成一個數組,如char[], byte[],也可以用其他方法取出其中某個特定位置的字元,如charAt();

與C裡面不同,在Java中,通常String用的比較多,char[]基本不用的。

閱讀全文

與java讀文件字元串相關的資料

熱點內容
cad2014教程pdf 瀏覽:199
怎麼遍歷伺服器同一類型的文件 瀏覽:436
惠普戰66畫圖編程 瀏覽:805
java面向對象作業 瀏覽:568
cad插件製作加密狗 瀏覽:923
cmd命令對話框 瀏覽:290
安卓應用怎麼常駐 瀏覽:676
安卓手機怎麼群發小費才不會被鎖 瀏覽:741
相機文件夾設置 瀏覽:855
centos7php怎麼用 瀏覽:119
查看linux操作系統版本的命令 瀏覽:382
收支預演算法怎麼做 瀏覽:875
模板如何上傳到伺服器 瀏覽:372
如何同步安卓信息到新ipad 瀏覽:364
騰訊雲輕量伺服器流量警告 瀏覽:503
u盤備份linux 瀏覽:120
高壓縮比活塞 瀏覽:92
壓縮彈簧標准件 瀏覽:25
linux統計個數命令 瀏覽:292
cad轉pdf居中 瀏覽:8