java檔案處理 之 讀寫TXT(比之c++,重設檔案頭,int轉string),檔案處理string

來源:互聯網
上載者:User

java檔案處理 之 讀寫TXT(比之c++,重設檔案頭,int轉string),檔案處理string

一:c/c++ 處理檔案的用法,詳見部落格 c++檔案操作

二:java與c++的方便之處:

(1) java在讀取檔案時,可以對字元流進行處理,重新進行編碼,如 InputStreamReader reader = new InputStreamReader(new FileInputStream(file),encoding);

 (2) BufferReader bufferReader = new BufferReader(file) 進行buffer處理

(3)java的非常好用的一點就是,伸手就來,如 int 轉 string  ( 如Integer.toString(intNumber) ),字串分隔(stringStr.split(exp); ) ,字串重新合成,直接加即可,非常好用;

(4)再藉助於整合式開發環境 IDE 缺少的依賴類,自動引入功能,更是如虎添翼。

三:處理TXT問檔案的樣本

package edu.tju.cs;import java.io.BufferedReader;import java.io.BufferedWriter;import java.io.File;import java.io.FileInputStream;import java.io.FileWriter;import java.io.InputStreamReader;public class OriginalDevideByTime {String times[] = {"6:00:00","6:30:00","7:00:00","7:30:00","8:00:00","8:30:00","9:00:00","9:30:00","10:00:00","10:30:00","11:00:00","11:30:00","12:00:00","12:30:00","13:00:00","13:30:00","14:00:00","14:30:00","15:00:00","15:30:00","16:00:00","16:30:00","17:00:00","17:30:00","18:00:00","18:30:00","19:00:00","19:30:00","20:00:00","20:30:00","21:00:00","21:30:00","22:00:00","22:30:00","23:00:00","23:30:00","24:00:00"};// 合成輸出檔案名public String getFileName(int cp){String fileName = "D:\\tjdata_metro\\results\\";fileName = fileName + Integer.toString(cp) + ".csv";return fileName;}// 讀取檔案,並分隔資料public void readTxtFile(String filePath){try {            String encoding="GBK";            File file=new File(filePath);            int cp = 1;            if(file.isFile() && file.exists()){ //判斷檔案是否存在                InputStreamReader read = new InputStreamReader(                new FileInputStream(file),encoding);//考慮到編碼格式                BufferedReader bufferedReader = new BufferedReader(read);                                String originalLine = null;                String newLine = null;                                while((originalLine = bufferedReader.readLine()) != null){                bufferedReader.mark((int)file.length()+1);// 設定檔案標誌位                                //寫入檔案名稱處理                if(cp >= times.length)                return;                String fileName = getFileName(cp);                BufferedWriter writer = new BufferedWriter(new FileWriter(new File(fileName)));                                while((originalLine = bufferedReader.readLine()) != null){                // 字串分隔                String tmp[] = originalLine.split(",");                // 如果符合重新合成                if(tmp.length>3)                if(tmp[3].compareTo(times[cp-1])>=0&&tmp[3].compareTo(times[cp])<0){                newLine = tmp[0] + "," + tmp[1] + "," + tmp[2] + "," + tmp[3] + "," + tmp[4] + "," + tmp[5] + "," + tmp[6] + "," + tmp[7];                System.out.println(newLine);                writer.write(newLine + "\n");                }                else                System.out.println("Not between times");                }                // 關閉寫檔案                writer.close();                // 重設為檔案開始位置,cp自加                bufferedReader.reset();                cp ++;                }                bufferedReader.close();                read.close();    }            else            {        System.out.println("OriginalDevideByTime……找不到指定的檔案");    }                } catch (Exception e) {        System.out.println("OriginalDevideByTime……讀取檔案內容出錯");        e.printStackTrace();    }System.out.println("OriginalDevideByTime……Devide is over!!!");}// main 函數入口 public static void main(String argv[]){        String filePath = "D:\\tjdata_metro\\TOKEN_ENEX_201404_20W.csv";        OriginalDevideByTime devide = new OriginalDevideByTime();                devide.readTxtFile(filePath);    }}

四:學習心得:

(1)JAVA中檔案指標複位到檔案開頭

File file = new File("temp.txt");  
BufferedReader  reader = null;  
reader = new BufferedReader(new FileReader(file));  
reader.mark((int)file.length()+1);  

// to do something

reader.reset();  
注意:如果檔案串的最後一個字元是中文,使用mark()中的長度設為file.length()
如果檔案的最後一個字串是英文或數字,則java.io.IOException: Mark invalid,使用mark()中的長度設為file.length()+1  

mark用於標記當前位置;在讀取一定數量的資料(小於readlimit的資料)後使用reset可以回到mark標記的位置;FileInputStream不支援mark/reset操作;BufferedInputStream支援此操作;
mark(readlimit)的含義是在當前位置作一個標記,制定可以重新讀取的最大位元組數,也就是說你如果標記後讀取的位元組數大於readlimit,你就再也回不到回來的位置了;通常InputStream的read()返回-1後,說明到達檔案尾,不能再讀取。除非使用了mark/reset

(2)JAVA中int轉String類型有三種方法
1》String.valueOf(i)
2》 Integer.toString(i)
3》 i+""
valueOf()和toString()方法可以明白,但為什麼3中加上一個""引號也可以?誰有資料可以看到?

(3)stringStr.compareTo(otherstring) ,相等返回 0 ,若是stringStr大於otherstring返回正數,若是stringStr小於otherstring返回負數


java讀取txt中的string與int

import java.awt.*;
import java.awt.event.*;
import java.io.*;
public class wenjian
{
public static void main(String[]str)
{
wenjian2 wj2=new wenjian2();
}
}
class wenjian2 extends Frame
{
public wenjian2()
{
setVisible(true);
//setSize(200,200);
TextArea tarea=new TextArea(8,26);
add(tarea);
byte byt[]=new byte[8];
pack();
this.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e)
{System.exit(0);}});

try{
FileInputStream fis=new FileInputStream(new File("D:\\a.txt"));
while((fis.read(byt,0,1)!=-1))
{
tarea.append(new String(byt,0,2));
}
fis.close();
}
catch(Exception ex)
{System.out.print(ex.getMessage().toString());}

}
}
 
java怎把txt檔案中的內容儲存至int數組(例如:txt中內容為222#11)(代碼)

public class NumJava {

int[] intNum ;

int[] displayNum(){
try {
FileReader fr = new FileReader("D:\\num.txt");

BufferedReader br = new BufferedReader(fr);
String line = null;
String strs[] = null;
StringBuilder sb = new StringBuilder();
while((line = br.readLine())!=null){
sb.append(line);
}
//去除空格 並以#分割
strs = sb.toString().trim().split("#");
//以讀取的字元數組 的長度 定義int數組長度
intNum = new int[strs.length];

for (int i = 0; i < strs.length; i++) {
intNum[i] = Integer.parseInt(strs[i]);
}

} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return intNum;
}

public static void main(String[] args) {
int [] intNum = new NumJava().displayNum();
for (int i : intNum) {
System.out.println(i);
}
}

}
 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.