導航:首頁 > 版本升級 > java對txt文件增刪改查

java對txt文件增刪改查

發布時間:2023-01-04 08:27:41

java 如何對讀入的txt文件進行修改啊。。。

這個是一行行讀的吧,讀到第一行的時候按位置修改分數,然後再輸出一個txt覆蓋掉原來的

Ⅱ 用JAVA實現對txt文件文本增刪改查

正好今天寫了個~原來是兩個類,好吧,加一個...= =~囧
以文件的形式存儲的

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Scanner;
import java.util.Set;

public class StudentManager {
private static File DB = new File("students.db");
private static Set<Student> studentList = null;

@SuppressWarnings("unchecked")
private static void initStudentList() {
if (DB.exists()) {
FileInputStream fi = null;
ObjectInputStream oi = null;
try {
fi = new FileInputStream(DB);
oi = new ObjectInputStream(fi);
Object obj = oi.readObject();
fi.close();
oi.close();
if (obj instanceof Set)
studentList = (Set<Student>) obj;
} catch (Exception e) {
e.printStackTrace();
}
}
if (studentList == null)
studentList = new HashSet<Student>();
}

private static void save() {
if (studentList == null)
return;
if (!DB.exists())
try {
DB.createNewFile();
} catch (Exception e) {
e.printStackTrace();
}
FileOutputStream fo;
try {
fo = new FileOutputStream(DB);
ObjectOutputStream oo = new ObjectOutputStream(fo);
oo.writeObject(studentList);
fo.close();
oo.close();
} catch (Exception e) {
e.printStackTrace();
}
}

private static Student[] getStudents(int id, String name) {
HashSet<Student> rlt = new HashSet<Student>();
if (id != 0) {
for (Student s : studentList) {
if (s.id == id)
rlt.add(s);
}
} else if (name != null && !name.isEmpty()) {
for (Student s : studentList) {
if (s._name.equalsIgnoreCase(name))
rlt.add(s);
}
}
return rlt.toArray(new Student[0]);
}

static {
initStudentList();
}
static void out(Object obj){
System.out.println(obj);
}

public static void menu() {
out("Welcome to use Student Manager!\n1-search student;\t2-add student;\t3-list all students;\nothers-exit");
Scanner in = new Scanner(System.in);
Student student = null;
String input = in.nextLine();
if (input.equals("1")) {
Student[] students = new Student[0];
out("please input name/id");
String ins = in.nextLine();
if (ins.matches("\\d+"))
students = getStudents(Integer.parseInt(ins), null);
else
students = getStudents(0, ins);
if (students.length != 0) {
out(Arrays.toString(students).replaceAll(
"\\[|\\]|, ", "\n"));
if (students.length == 1)
student = students[0];
else {
out("please choose a student by id:\n");
int i = in.nextInt();
for (Student s : students) {
if (s.id == i) {
student = s;
break;
} else {
out("error");
menu();
}
}
}
out("1-set score;\t2-delete score;\t3-delete student;\tother-exit");
int input1=in.nextInt();
in.nextLine();
String course=null;
float score=0;
switch(input1){
case 1:
out("please input course");
course=in.nextLine();
out("please input score");
score = in.nextFloat();
in.nextLine();
student.setScore(course, score);
break;
case 2:
out("please input course");
course=in.nextLine();
student.removeScore(course);
break;
case 3:
student.removeFrom(studentList);
break;
}
}
else {
out("NO current record!");
}
}
if (input.equals("2")) {
out("please input id");
int id=in.nextInt();
in.nextLine();
out("please input name");
String name = in.nextLine();
out("please input class");
String cname=in.nextLine();
student=new Student(id, name, cname);
if(studentList.add(student)){
out("create success!\n");
String input2="-";
while(!input2.isEmpty()){
out("set score? \n1-yes;\t2-no");
input2=in.nextLine();
if(input2.equals("1")){
out("please input course");
String course=in.nextLine();
out("please input score");
float score = in.nextFloat();
student.setScore(course, score);
in.nextLine();
}
else break;
}
}else out("Error: id or student exists");
}
if (input.equals("3")) {
out(studentList.toString().replaceAll("\\[|\\]|, ", "\n"));
}
if(input.isEmpty())return;
save();
menu();
}

public static void main(String[] args){
menu();
}
}

class Student implements Serializable {
public String toString() {
return "id: " + id + "\tclass: " + _class + "\tname: " + _name
+ courses.toString().replaceAll("\\{|\\}|, ", "\n").replaceAll("=", ": ");
}

Student(int id, String _name, String _class) {
this.id = id;
this._class = _class;
this._name = _name;
}

private static final long serialVersionUID = 1L;
public int id = 0;

public String _name = "";
public String _class = "";
HashMap<String, Float> courses = new HashMap<String, Float>();

void setScore(String course, float score) {
courses.put(course, score);
System.out.println("set success!\n\n"+this);
}

void removeScore(String course) {
courses.remove(course);
System.out.println("delete success!\n\n"+this);
};

void removeFrom(Set<?> list) {
list.remove(this);
System.out.println("delete success!");
}

public int hashCode() {
return 31;
}

public boolean equals(Object obj) {
Student s = null;
if(obj instanceof Student){
System.out.println(1);
s=(Student)obj;
return s.id==id||(s._class.equals(_class)&&s._name.equals(_name));
}
return false;
}
}
class DaJiangYou{
DaJiangYou(){
System.out.println("I am da jiang you");
}
}

Ⅲ java文件流txt文檔內容增刪改

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;

public class UpdateTxt {

static List<String> txt = new ArrayList<String>();
public static void main(String[] args) {
read("D:/lj/12.txt");
// add(2,"asd");
delete(2);
// addToFinal("asd");
write("D:/lj/12.txt");
}
//讀取
public static void read(String path){
String temp = null;
int i = 0;
try {
BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(path)));
while((temp = br.readLine()) != null){
txt.add(temp);
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
//寫回
public static void write(String path){
try {
PrintWriter pw = new PrintWriter(new OutputStreamWriter(new FileOutputStream(path)));
for(int i = 0; i<txt.size() ; i++){
pw.println(txt.get(i));
pw.flush();
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
//添加到第幾行
public static void add(int line , String s){
txt.add(line-1, s);
}
//刪除某行
public static void delete(int line){
txt.remove(line - 1);
}

//添加到最後
public static void addToFinal(String s){
txt.add(s);
}

}

Ⅳ java io流對文件的增刪改查

可以通過BufferedReader 流的形式進行流讀取,之後通過readLine方法獲取到的內容,之後通過if判斷來實現在某些特定位置的查找、增加、刪除、修改操作。
舉例:
BufferedReader bre = null;
OutputStreamWriter pw = null;//定義一個流
try {
String file = "D:/test/test.txt";
bre = new BufferedReader(new FileReader(file));//此時獲取到的bre就是整個文件的緩存流
pw = new OutputStreamWriter(new FileOutputStream(「D:/test.txt」),"GBK");//確認流的輸出文件和編碼格式,此過程創建了「test.txt」實例
while ((str = bre.readLine())!= null) // 判斷最後一行不存在,為空結束循環
{
if(str.indexOf("排除")<0){//判斷是否需要舍棄
pw.write(str);//將要寫入文件的內容,可以多次write
}
}
bre.close();//關閉流
pw.close();//關閉流
解釋:以上方法是實現的刪除,if中的條件改變下,即可實現其餘的功能。
備註:文件流用完之後必須及時通過close方法關閉,否則會一直處於打開狀態,直至程序停止,增加系統負擔。

Ⅳ 如何通過java實現對指定目錄下的txt文件進行增刪改查

代碼如下:

importjava.io.BufferedReader;
importjava.io.BufferedWriter;
importjava.io.FileInputStream;
importjava.io.FileOutputStream;
importjava.io.IOException;
importjava.io.InputStreamReader;
importjava.io.OutputStreamWriter;
importjava.util.ArrayList;
importjava.util.List;

publicclassApp61{

publicstaticvoidmain(String[]args)throwsIOException{

//查找行輸出
Stringline=findFileLine("mylist.txt","abc");
System.out.println(line);

//刪除指定行
removeFileLine("mylist.txt",2);
}

staticvoidremoveFileLine(Stringfile,intline)throwsIOException{

List<String>lines=readFileLines(file);

lines.remove(line-1);

FileOutputStreamoutputStream=null;

=null;

BufferedWriterwriter=null;

try{

outputStream=newFileOutputStream(file);

streamWriter=newOutputStreamWriter(outputStream);

writer=newBufferedWriter(streamWriter);

for(Stringstr:lines){
writer.write(str+System.lineSeparator());
}

}finally{
if(writer!=null){
writer.close();
}
if(streamWriter!=null){
streamWriter.close();
}
if(outputStream!=null){
outputStream.close();
}
}
}


//查找行
staticStringfindFileLine(Stringfile,Stringkeywork)throwsIOException{

List<String>lines=readFileLines(file);

for(Stringline:lines){
if(line.contains(keywork)){
returnline;
}
}

return"";
}

//返迴文件所有行
staticList<String>readFileLines(Stringfile)throwsIOException{

List<String>lines=newArrayList<>();

FileInputStreaminputStream=null;

InputStreamReaderstreamReader=null;

BufferedReaderreader=null;

try{

inputStream=newFileInputStream(file);

streamReader=newInputStreamReader(inputStream);

reader=newBufferedReader(streamReader);

Stringline="";

while((line=reader.readLine())!=null){
lines.add(line);
}
}finally{
if(reader!=null){
reader.close();
}
if(streamReader!=null){
streamReader.close();
}
if(inputStream!=null){
inputStream.close();
}
}

returnlines;
}
}

Ⅵ Java實現對txt的增刪改查中,怎麼把txt中重名的幾條信息都刪了。比如txt中有好多人的信息,

  1. 使用java讀取txt文件,使用List集合

  2. 判斷List集合中重復信息,如果重復,刪除

  3. 請採納 謝謝

    publicstaticvoidmain(String[]args){
    List<String>values=newArrayList<String>();

    Map<String,Boolean>map=newHashMap<String,Boolean>();

    try{
    BufferedReaderbf=newBufferedReader(newInputStreamReader(newFileInputStream("d:/d.txt")));
    Stringvalue="";
    while((value=bf.readLine())!=null){
    value=value.trim();
    if(!value.equals("")){
    if(map.get(value)==null){
    values.add(value);
    map.put(value,true);
    }
    }
    }
    for(Stringstring:values){
    System.out.println(string);
    }
    }catch(FileNotFoundExceptione){
    //TODOAuto-generatedcatchblock
    e.printStackTrace();
    }catch(IOExceptione){
    //TODOAuto-generatedcatchblock
    e.printStackTrace();
    }

    }

Ⅶ 用java在txt文件下對文件進行增刪改查,是否需要用流先給txt文件讀入

一般來說,只要不是對文件進行讀寫,是不需要流的。但涉及到文件內容的讀和寫,肯定需要流

Ⅷ 用java讀寫txt格式文件里的數據,並實現對數據的增刪改查,求大神知道一二,小弟剛涉足,不是太懂。,

實體類:
AAA屬性 id,testDate,road,num1,type1,num2,type2 記得添加get,set方法.
每讀取一行時值添加到AAA實體類對應屬性中,然後add至List。

樓主用好StringTokenizer 不建議用了,用string.split()方法吧 。
循環:
AAA bean = null;
List<AAA> list = new ArrayList<AAA>();
while (...)
{
bean = new AAA();
String[] arr = s.split("空格數自定");
String id = arr[0].trim();
String testDate= arr[1].trim();//考慮是否轉為時間格式
//依次讀取

//將讀取的值錄入到bean中
bean.setId(id);
bean.setTestDate(testDate);
//...依次錄入

list.add(bean);//將值添加到集合中
}
//OK ,真累!

Ⅸ 用java在圖形用戶界面下的txt文件下對文件進行增刪改查

就寫個新增的吧。其他你照著寫。

package com.zz.jfram;

import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.IOException;

import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.JTextField;

public class TxtManage extends JFrame {

private static final long serialVersionUID = 1L;

public TxtManage() {
final JFrame jFrame = new JFrame();
JButton jButton = new JButton("新增");
JPanel jPanel = new JPanel();
final JTextField jTextField = new JTextField(30);
final JLabel jLabel = new JLabel("請輸入新增文件的名字:");
jPanel.add(jLabel, FlowLayout.LEFT);
jPanel.add(jTextField, FlowLayout.CENTER);
jPanel.add(jButton, FlowLayout.RIGHT);
jFrame.add(jPanel, BorderLayout.NORTH);
// 設置窗體屬性
jFrame.setBounds(500, 50, 600, 400);
final JTextArea jTextArea = new JTextArea(50, 50);

// 新增按鈕點擊事件
jButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
JFileChooser jfc = new JFileChooser();
jfc.setDialogTitle("選擇路徑");
jfc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);// 只能選擇目錄
if (jfc.showOpenDialog(jFrame) == JFileChooser.APPROVE_OPTION) {
// 選中目錄的絕對路徑
String path = jfc.getSelectedFile().getAbsolutePath();
// 在當前目錄新增一個文件
File file = new File(path+"\\"+jTextField.getText()+".txt");
if (!file.exists()) {
try {
file.createNewFile();
jTextArea.setText("文件新增成功!");
} catch (IOException e1) {
e1.printStackTrace();
}
}else{
try {
throw new Exception("文件已存在!");
} catch (Exception e1) {
e1.printStackTrace();
}
}

}
}
});
jFrame.add(jTextArea, BorderLayout.CENTER);
jFrame.setVisible(true);
// 關閉處理動作
jFrame.setDefaultCloseOperation(EXIT_ON_CLOSE);
}

public static void main(String[] args) {
new TxtManage();
}

}

Ⅹ 用Java寫一個基於txt文本的控制台輸入的增刪查改

packagecom.list;
/*
*Author:qcq
*Date:2015/7/20
*E-mail:[email protected]
**/
importjava.io.BufferedReader;
importjava.io.File;
importjava.io.FileReader;
importjava.io.FileWriter;
importjava.io.IOException;
importjava.util.HashMap;
importjava.util.Map;
importjava.util.Scanner;
importjava.util.Set;

publicclassQuery{
classPerson{
publicStringId;/*shouldbesurethisisunique*/
publicStringname;
publicintage;
publicbooleansex;/*trueforman,falseforgirl*/
@Override
publicStringtoString(){
returnId+""+name+""+age+""+(sex?"M":"F");
}

}
privateMap<String,Person>people;
privateStringfileName;
publicQuery(StringfileName){
people=newHashMap<String,Person>();
this.fileName=fileName;
if(!initial()){
System.out.println(""
+"storefilepath,pleasecheckit,andrerunthisprogram.");
}
}
privatebooleaninitial(){
booleanflag=false;
try{
Filefile=newFile(fileName);
if(!file.exists()){
System.out.println("Thefilenotexist,wewillcreateitforyou");
file.createNewFile();
}
BufferedReaderreader=newBufferedReader(newFileReader(fileName));
Stringline=reader.readLine();
while(null!=line&&!line.equals("")){
String[]splitLine=line.split("+");
if(splitLine.length<4){
System.out.println("Theinformationnotenough");
returnflag;
}
Persontemp=newPerson();
temp.Id=splitLine[0];
temp.name=splitLine[1];
temp.age=Integer.valueOf(splitLine[2]);
temp.sex=splitLine[3].equals("M")?true:false;
people.put(temp.Id,temp);
line=reader.readLine();
}
flag=true;
}catch(IOExceptione){
e.printStackTrace();
}
returnflag;
}
publicbooleanwriteInFile(){
booleanflag=false;
try{
FileWriterwriter=newFileWriter(fileName);
Set<String>key=people.keySet();
for(StringkeyIndex:key){
writer.write(people.get(keyIndex).toString()+" ");
}
}catch(IOExceptione){
e.printStackTrace();
}

returnflag;
}
/**/
publicbooleanadd(){
returnfalse;
}
publicbooleandelete(){
returnfalse;
}
publicbooleanquery(){
returnfalse;
}
publicbooleanupdate(){
returnfalse;
}
publicstaticvoidmain(String[]args){
Querydata=newQuery("temp.txt");/*hereshoulddefinethefilename*/
Scannerin=newScanner(System.in);
System.out.println("Hereyoucanchoicewhichoption: "
+"quit:forquit"
+"a:foradd"
+"d:fordelete"
+"u:forupdate"
+"q:forquery");
Stringoption=in.next();
label:
while(null!=option&&!option.equals("")){
switch(option){
case"quit":breaklabel;
case"a":
/*hereaddthefunction*/
data.add();
break;
case"d":
/*hereaddthefunction*/
data.delete();
break;
case"u":
/*hereaddthefunction*/
data.update();
break;
case"q":
/*hereaddthefunction*/
data.query();
break;
default:
breaklabel;
}
}
if(null!=in){
in.close();
}
}
}

閱讀全文

與java對txt文件增刪改查相關的資料

熱點內容
c語言將通訊錄文件導入管理系統 瀏覽:828
cad文件圖標變成白板如何恢復 瀏覽:190
貴州遵義開發票下載什麼網站 瀏覽:496
如何獲取美團的銷售數據 瀏覽:575
大數據建模的方法有哪些 瀏覽:958
分公司工商年報如何填寫財務數據 瀏覽:286
蘋果北京維修點地址 瀏覽:928
app原型圖是什麼東西 瀏覽:237
ug直接用cad文件建模 瀏覽:272
蘋果電腦打開mp4文件 瀏覽:337
數據線一直發燙怎麼回事 瀏覽:830
IBM代碼5 瀏覽:279
編程時如何讓輸出結果之間有空格 瀏覽:112
怎麼復制網上文件 瀏覽:675
蘋果怎麼關掉網站禁止訪問 瀏覽:478
win10適合機械硬碟嗎 瀏覽:586
qq頭像歐美男霸氣頭像 瀏覽:368
java批量修改數據返回值 瀏覽:517
wp81創建文件夾 瀏覽:968
iphone高科技軟體 瀏覽:654

友情鏈接