java 如何使用Java读取和更新文件中的行
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5119335/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to read and update row in file with Java
提问by 1myb
currently i creating a java apps and no database required that why i using text file to make it the structure of file is like this
目前我创建了一个java应用程序并且不需要数据库,为什么我使用文本文件来使它的文件结构是这样的
unique6id username identitynumber point
unique6id username identitynumber point
may i know how could i read and find match unique6id then update the correspond row of point ?
我可以知道如何读取并找到匹配的 unique6id 然后更新相应的点行吗?
Sorry for lack of information and here is the part i type is
抱歉缺少信息,这是我输入的部分
public class Cust{
string name;
long idenid, uniqueid;
int pts;
customer(){}
customer(string n,long ide, long uni, int pt){
name = n;
idenid = ide;
uniqueid = uni;
pts = pt;
}
FileWriter fstream = new FileWriter("Data.txt", true);
BufferedWriter fbw = new BufferedWriter(fstream);
Cust newCust = new Cust();
newCust.name = memUNTF.getText();
newCust.ic = Long.parseLong(memICTF.getText());
newCust.uniqueID = Long.parseLong(memIDTF.getText());
newCust.pts= points;
fbw.write(newCust.name + " " + newCust.ic + " " + newCust.uniqueID + " " + newCust.point);
fbw.newLine();
fbw.close();
this is the way i text in the data then the result inside Data.txt is
这是我在数据中文本的方式,然后 Data.txt 中的结果是
spencerlim 900419129876 448505 0
Eugene 900419081234 586026 0
when user type in 586026 then it will grab row of eugene bind into Cust and update the pts (0 in this case, try to update it into other number eg. 30)
当用户输入 586026 时,它会将 eugene bind 的行抓取到 Cust 中并更新 pts(在这种情况下为 0,尝试将其更新为其他数字,例如 30)
Thx for reply =D
谢谢回复 =D
回答by Tom Anderson
Reading is pretty easy, but updating a text file in-place (ie without rewriting the whole file) is very awkward.
阅读很容易,但就地更新文本文件(即不重写整个文件)非常尴尬。
So, you have two options:
所以,你有两个选择:
Read the whole file, make your changes, and then write the whole file to disk, overwriting the old version; this is quite easy, and will be fast enough for small files, but is not a good idea for very large files.
Use a format that is not a simple text file. A database would be one option (and bear in mind that there is one, Derby, built into the JDK); there are other ways of keeping simple key-value stores on disk (like a HashMap, but in a file), but there's nothing built into the JDK.
读取整个文件,进行更改,然后将整个文件写入磁盘,覆盖旧版本;这很容易,并且对于小文件来说足够快,但对于非常大的文件来说不是一个好主意。
使用不是简单文本文件的格式。数据库将是一种选择(请记住,JDK 中内置了一个,Derby);还有其他方法可以将简单的键值存储保存在磁盘上(如 HashMap,但在文件中),但 JDK 中没有内置任何内容。
回答by Sean Patrick Floyd
You can use OpenCSV with custom separators.
您可以使用带有自定义分隔符的 OpenCSV。
Here's a sample method that updates the info for a specified user:
这是更新指定用户信息的示例方法:
public static void updateUserInfo(
String userId, // user id
String[] values // new values
) throws IOException{
String fileName = "yourfile.txt.csv";
CSVReader reader = new CSVReader(new FileReader(fileName), ' ');
List<String[]> lines = reader.readAll();
Iterator<String[]> iterator = lines.iterator();
while(iterator.hasNext()){
String[] items = (String[]) iterator.next();
if(items[0].equals(userId)){
for(int i = 0; i < values.length; i++){
String value = values[i];
if(value!=null){
// for every array value that's not null,
// update the corresponding field
items[i+1]=value;
}
}
break;
}
}
new CSVWriter(new FileWriter(fileName), ' ').writeAll(lines);
}
回答by AlexR
Use InputStream(s) and Reader(s) to read file. Here is a code snippet that shows how to read file.
使用 InputStream(s) 和 Reader(s) 读取文件。这是一个显示如何读取文件的代码片段。
BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream("c:/myfile.txt")));
String line = null;
while ((line = reader.readLine()) != null) {
// do something with the line.
}
Use OutputStream and Writer(s) to write to file. Although you can use random access files, i.e. write to the specific place of the file I do not recommend you to do this. Much easier and robust way is to create new file every time you have to write something. I know that it is probably not the most efficient way, but you do not want to use DB for some reasons... If you have to save and update partial information relatively often and perform search into the file I'd recommend you to use DB. There are very light weight implementations including pure java implementations (e.g. h2: http://www.h2database.com/html/main.html).
使用 OutputStream 和 Writer(s) 写入文件。虽然您可以使用随机访问文件,即写入文件的特定位置,但我不建议您这样做。更简单和健壮的方法是每次必须写一些东西时创建新文件。我知道这可能不是最有效的方法,但是由于某些原因您不想使用 DB...如果您必须相对频繁地保存和更新部分信息并在文件中执行搜索,我建议您使用D B。有非常轻量级的实现,包括纯 java 实现(例如 h2:http: //www.h2database.com/html/main.html)。