当我尝试将数据保存在 txt (java) 中时,为什么会出现这些符号

发布于 2024-12-19 18:12:26 字数 4609 浏览 1 评论 0原文

在您认为这太长之前,请尝试帮助我解决这个问题,我一整天(上午 9:52 - 下午 4:54)都在处理这个问题,它只是困扰着我。

我似乎无法正确保存这些数据我主要有双精度数和字符串,我将它们保存在名为“autosAudi.txt”的.txt文件中,我得到这些奇怪的代码和框,有时出于某种原因在我的文本字段中出现中文?以下是显示内容的示例:

http://www.flickr.com/photos/63259070 @N06/6449175293

正如你所看到的,这些奇怪的盒子无处不在,我没有注册任何类似的东西,就像我一样通过单击>>浏览数据(下一个)或<< (上一篇)并且信息应该改变,“Numero”旁边的文本字段应该为我提供一种输入 int 代码的方法,以便我可以搜索数据(例如,如果我写 1,它应该找到该注册表)。它只适用于数字 1,之后它给出了这个错误:

run:
3-Dec-2011 5:02:01 PM rent_autos.Interfaz3 jbBucar_AMouseClicked
SEVERE: null
java.io.EOFException
at java.io.RandomAccessFile.readChar(RandomAccessFile.java:695)
at rent_autos.Autos.leerCadena(Autos.java:276)
at rent_autos.Autos.buscar(Autos.java:344)
at rent_autos.Interfaz3.jbBucar_AMouseClicked(Interfaz3.java:4640)
at rent_autos.Interfaz3.access$1100(Interfaz3.java:30)
at rent_autos.Interfaz3$12.mouseClicked(Interfaz3.java:745)
at java.awt.Component.dispatchEventImpl(Component.java:4630)
at java.awt.Container.dispatchEventImpl(Container.java:2099)
java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:269)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:184)
java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:174)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:169)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:161)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:122) 

这是我用于将文件保存在“autosAudi.txt”中的代码:

public void guardar() throws IOException    {
int opcion = JOptionPane.showConfirmDialog(null,"¿Desea guardar los                  
cambios?","Datos Persona",JOptionPane.YES_NO_CANCEL_OPTION);


if(opcion == 0){
RandomAccessFile f = new RandomAccessFile("autosAudi.txt","rw");
f.seek(f.length());
f.writeInt(codigo);
f.writeDouble(costo);
f.writeDouble(rendimientoGalon);
escribirCadena(f, ACRISS);
escribirCadena(f, color);
escribirCadena(f, modelo);
escribirCadena(f, tipoAM);
escribirCadena(f, placa);
escribirCadena(f, marca );

f.close();
}

}

还使用了:

public boolean cargarDatosRegistro(long iPosicion, String sRuta){
boolean bRealizado = true;
try {
RandomAccessFile fRegistro = new RandomAccessFile(sRuta,"rw");
fRegistro.seek(iPosicion);
codigo  = fRegistro.readInt();
costo = fRegistro.readDouble();
rendimientoGalon  = fRegistro.readDouble();
ACRISS  = leerCadena(fRegistro);
color  = leerCadena(fRegistro);
modelo = leerCadena(fRegistro);
tipoAM = leerCadena(fRegistro);
placa = leerCadena(fRegistro); 
marca = leerCadena(fRegistro);

fRegistro.close();
} catch (Exception e) {
bRealizado = false;
}
return bRealizado;
}

escribirCadena 方法用于 String 类型,因为 java 不有 .writeString,这是该代码:

private void escribirCadena( RandomAccessFile file, String cadena) throws IOException               
{    
StringBuffer buffer = (cadena == null)? new StringBuffer(15): 
new         StringBuffer(cadena);
buffer.setLength(30);
file.writeChars(buffer.toString());
}

leerCadena 方法用于读取字符串:

private String leerCadena( RandomAccessFile file ) throws IOException   {
char cadena[] = new char[30], temp;
for ( int c=0;c<cadena.length;c++)
{
temp = file.readChar();
cadena[c]=temp;
}
return new String(cadena).replace('\0',' ');
}

我根据导师的示例制作了这个项目,文件确实不同,这是图片:

http://www.flickr.com/photos/63259070@N06/6449172477/在/photostream/

写着“Registro.txt”的是我的老师和“autosAudi.txt”是我的

最后一件事:搜索方法有点长:

public void buscar(int cod) throws IOException{
RandomAccessFile f = new RandomAccessFile("autosAudi.txt","rw");
boolean encontrado=false;
registroExistente = false ;
long bytes = 0;
do{
codigo = f.readInt();
costo = f.readDouble();
rendimientoGalon = f.readDouble();
ACRISS = leerCadena(f);
color = leerCadena(f);
modelo = leerCadena(f);
tipoAM = leerCadena(f);
placa = leerCadena(f);
marca = leerCadena(f);

if(cod==codigo){
iCodigoBusqueda = codigo;
encontrado=true;
registroExistente = true;
break;
}else{
iCodigoBusqueda = 0;
registroExistente = false;
}
bytes += iTamanioRegistro;
f.seek(bytes);
}
while(bytes<f.length());

if(!encontrado){
registroExistente = false;
JOptionPane.showMessageDialog(null,"Archivo no encontrado");
}
f.close();
}

所以有人可以帮我吗!,这真的很棒,我知道它有点长,但如果有人有解决问题的知识请分享,是的,我尝试过 .dat 文件类型

Before you think that this is to long just please try to help me out ive been on this issue all day(9:52 AM - 4:54 PM), its just bugging me.

I cant seem to save these data correctly I have mainly doubles and strings, I am saving these in a .txt file called "autosAudi.txt", I get these weird codes and boxes and sometimes for whatever reason Chinese in my textfields? Here is a example of what appears:

http://www.flickr.com/photos/63259070@N06/6449175293

as you can see these weird boxes appear out nowhere I didnt register nothing like that, the way I navigate through the data is by clicking >> (next) or << (previous) and the information is supposed to change, the textfield next to "Numero" is supposed to give me a way to input an int code so I can search the data(for example if I write 1, its supposed to find that registry). it only works for the number 1 and after that it gives this error:

run:
3-Dec-2011 5:02:01 PM rent_autos.Interfaz3 jbBucar_AMouseClicked
SEVERE: null
java.io.EOFException
at java.io.RandomAccessFile.readChar(RandomAccessFile.java:695)
at rent_autos.Autos.leerCadena(Autos.java:276)
at rent_autos.Autos.buscar(Autos.java:344)
at rent_autos.Interfaz3.jbBucar_AMouseClicked(Interfaz3.java:4640)
at rent_autos.Interfaz3.access$1100(Interfaz3.java:30)
at rent_autos.Interfaz3$12.mouseClicked(Interfaz3.java:745)
at java.awt.Component.dispatchEventImpl(Component.java:4630)
at java.awt.Container.dispatchEventImpl(Container.java:2099)
java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:269)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:184)
java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:174)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:169)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:161)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:122) 

Here is the code that I used for saving the file in the "autosAudi.txt":

public void guardar() throws IOException    {
int opcion = JOptionPane.showConfirmDialog(null,"¿Desea guardar los                  
cambios?","Datos Persona",JOptionPane.YES_NO_CANCEL_OPTION);


if(opcion == 0){
RandomAccessFile f = new RandomAccessFile("autosAudi.txt","rw");
f.seek(f.length());
f.writeInt(codigo);
f.writeDouble(costo);
f.writeDouble(rendimientoGalon);
escribirCadena(f, ACRISS);
escribirCadena(f, color);
escribirCadena(f, modelo);
escribirCadena(f, tipoAM);
escribirCadena(f, placa);
escribirCadena(f, marca );

f.close();
}

}

And also used:

public boolean cargarDatosRegistro(long iPosicion, String sRuta){
boolean bRealizado = true;
try {
RandomAccessFile fRegistro = new RandomAccessFile(sRuta,"rw");
fRegistro.seek(iPosicion);
codigo  = fRegistro.readInt();
costo = fRegistro.readDouble();
rendimientoGalon  = fRegistro.readDouble();
ACRISS  = leerCadena(fRegistro);
color  = leerCadena(fRegistro);
modelo = leerCadena(fRegistro);
tipoAM = leerCadena(fRegistro);
placa = leerCadena(fRegistro); 
marca = leerCadena(fRegistro);

fRegistro.close();
} catch (Exception e) {
bRealizado = false;
}
return bRealizado;
}

The escribirCadena method is used on String types, because java doesnt have .writeString, heres the code for that:

private void escribirCadena( RandomAccessFile file, String cadena) throws IOException               
{    
StringBuffer buffer = (cadena == null)? new StringBuffer(15): 
new         StringBuffer(cadena);
buffer.setLength(30);
file.writeChars(buffer.toString());
}

And the leerCadena Method is for reading Strings:

private String leerCadena( RandomAccessFile file ) throws IOException   {
char cadena[] = new char[30], temp;
for ( int c=0;c<cadena.length;c++)
{
temp = file.readChar();
cadena[c]=temp;
}
return new String(cadena).replace('\0',' ');
}

I made this project based on the example of my tutor and the files are really different, heres the pic:

http://www.flickr.com/photos/63259070@N06/6449172477/in/photostream/

The one that says "Registro.txt" is my teachers and the "autosAudi.txt" is mine

Heres one last thing: the search method kind of long:

public void buscar(int cod) throws IOException{
RandomAccessFile f = new RandomAccessFile("autosAudi.txt","rw");
boolean encontrado=false;
registroExistente = false ;
long bytes = 0;
do{
codigo = f.readInt();
costo = f.readDouble();
rendimientoGalon = f.readDouble();
ACRISS = leerCadena(f);
color = leerCadena(f);
modelo = leerCadena(f);
tipoAM = leerCadena(f);
placa = leerCadena(f);
marca = leerCadena(f);

if(cod==codigo){
iCodigoBusqueda = codigo;
encontrado=true;
registroExistente = true;
break;
}else{
iCodigoBusqueda = 0;
registroExistente = false;
}
bytes += iTamanioRegistro;
f.seek(bytes);
}
while(bytes<f.length());

if(!encontrado){
registroExistente = false;
JOptionPane.showMessageDialog(null,"Archivo no encontrado");
}
f.close();
}

So can anyone help me out here!, it would be really great I know its kind of long but if anyone has the knowledge to solve this please share, and yes I haved tries .dat file types

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

也只是曾经 2024-12-26 18:12:26

您的代码有几个问题,我将尝试指出最明显的问题以及如何修复它们。

你说你的 RandomAccessFile 没有办法存储字符串,所以你从你的 String 创建一个 StringBuffer,从中创建一个 String 并存储它。您正在使用存储字符串的方法,不要先创建 StringBuffer。您还将 StringBuffer 的原始容量设置为 30,并且似乎认为这意味着它将始终为 30 个字符。事实并非如此,它只能存储 30 个字符而不调整自身大小。

当读回字符串时,这会导致下一个问题。即使您的字符串不是 30 个字符,您也始终会读取 30 个字符。这会将不属于它的数据放入您的字符串中。然后,您尝试通过用空格替换空字符来删除这些字符。

您想要用于存储字符串的是

RandomAccessFile.writeUTF(theString)

它存储字符串的长度及其字符。要再次读回它,您应该使用

RandomAccessFile.readUTF()

如果您想使用 writeChars,您首先需要存储字符串的长度,以便您知道从文件读取时要读回多少个字符。

这是一个简短的例子,它是如何工作的

    RandomAccessFile f = new RandomAccessFile("theRandomeAccessFile", "rw");
    f.writeInt(1);
    f.writeDouble(2.34);
    f.writeUTF("SomeString");
    f.writeChar('C');
    f.seek(0);
    System.err.println(f.readInt());
    System.err.println(f.readDouble());
    System.err.println(f.readUTF());
    System.err.println(f.readChar());

There are several things wrong with your code and I'll try to point out the most obvious ones and how to fix them.

You say your RandomAccessFile does not have a way to store stings, so instead you create a StringBuffer from your String, create a String out of it and store it. You are using a method that stores strings, do not first create a StringBuffer. You also set the original capacity of the StringBuffer to 30 and seem to think that this means it will always be 30 characters. This is not so, it will only be able to store 30 characters without resizing itself.

This is causing your next problem when reading the string back. You always read 30 characters even though your string wasn't 30 characters. This gets data into your string which does not belong to it. These you then try to remove by replacing null characters with spaces.

What you want to use for storing your string is

RandomAccessFile.writeUTF(theString)

This stores the length of the string and the characters of it. For reading it back again you should use

RandomAccessFile.readUTF()

If you want to use writeChars you first need to store the length of your string so you know how many to read back when reading from the file.

This is a short example how it would work

    RandomAccessFile f = new RandomAccessFile("theRandomeAccessFile", "rw");
    f.writeInt(1);
    f.writeDouble(2.34);
    f.writeUTF("SomeString");
    f.writeChar('C');
    f.seek(0);
    System.err.println(f.readInt());
    System.err.println(f.readDouble());
    System.err.println(f.readUTF());
    System.err.println(f.readChar());
度的依靠╰つ 2024-12-26 18:12:26

RandomAccessFilewriteIntwriteDouble 等方法以二进制形式写入其参数。如果您想要一个文本文件,请使用 FileWriter,或者如果您想使用与默认平台不同的编码,请使用包装 FileOutputStreamOutputStreamWriter编码。类似地,使用 FileReader 或包装 FileInputStream 的 InputStreamReader 来读取文本文件。

如果要存储和读取文本文件中的结构化数据,最好选择易于解析的格式,例如 XML 或 JSON,而不是实现自己的协议。

关于您遇到的错误,您的代码太大且复杂,无法调试。如果您希望我们能够进行调试,请发布 SSCCE。

阅读 IO 教程:http://docs.oracle.com/javase/教程/essential/io/charstreams.html

The writeInt, writeDouble, etc. methods of RandomAccessFile write their argument in binary form. If you want a text file, use a FileWriter, or an OutputStreamWriter wrapping a FileOutputStream if you want to use an encoding different from the default platform encoding. Similarly, use a FileReader or an InputStreamReader wrapping a FileInputStream to read the text file.

If you want to store and read structured data from a text file, you'd better choose an easily parseable format like XML or JSON, rather than implementing your own protocol.

Regarding the bug you have, your code is too large and complex to debug it. Post a SSCCE if you want us to be able to debug.

Read the IO tutorial: http://docs.oracle.com/javase/tutorial/essential/io/charstreams.html

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文