导航:首页 > 版本升级 > 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文件增删改查相关的资料

热点内容
文件打印页面边距多少 浏览:503
电商网站叫什么名字好 浏览:726
win1014393更新 浏览:751
电脑计算器文件类型是多少 浏览:671
wsdl地址生成wsdl文件 浏览:798
系统会同时保存多少文件夹 浏览:63
劳务费app怎么申请缴税 浏览:575
dw最新版本如何建立网站 浏览:799
wps表格怎样取消密码设置密码 浏览:135
老黄历哪个网站好 浏览:316
rar是文件怎么打开 浏览:395
java开发app的架构 浏览:865
ppt怎么放音频文件 浏览:874
app被骗钱怎么找回 浏览:813
型动app怎么做教练 浏览:364
雪佛兰车载app怎么样 浏览:133
637的微信版本如何建百人群 浏览:41
外梯形螺纹怎么编程 浏览:986
vs2010vb工具箱 浏览:938
win10重装多少钱 浏览:662

友情链接