Read to a Null Char?
Hello Java Forum,
I read in a char szText[256] is there a way to stop reading at the null char?
I don't want to read the whole array if I don't have to.
Thanks
How else is it going to be done? If there (hypothetically) was a method that read in a null-terminated string, that's what it would have to do if you looked inside it.
Similar Messages
-
Reading .txt file into char array, file not found error. (Basic IO)
Iv been having some trouble with reading characters from a text file into a char array. I havnt been learning io for very long but i think im getting the hang of it. Reading and writing raw bytes
and things like that. But i wanted to try using java.io.FileReader to read characters for a change and im having problems with file not found errors. here is the code.
try
File theFile = new File("Mr.DocumentReadMe.txt");
String path = theFile.getCanonicalPath();
FileReader readMe = new FileReader(path);
char buffer[] = new char[(int)theFile.length()];
int readData = 0;
while(readData != -1)
readData = readMe.read(buffer);
jEditorPane1.setText(String.valueOf(buffer));
catch(Exception e)
JOptionPane.showMessageDialog(null, e,
"Error!", JOptionPane.ERROR_MESSAGE);
The error is: java.io.FileNotFoundException: C:\Users\Kaylan\Documents\NetBeansProjects\Mr.Document\dist\Mr.DocumentReadMe.txt (The system cannot find the file specified)
The text file is saved in the projects dist folder. I have tried saving it elsewhere and get the same error with a different pathname.
I can use JFileChooser to get a file and read it into a char array with no problem, why doesnt it work when i specify the path manually in the code?Well the file clearly isn't there. Maybe it has a .txt.txt extensionthat Windows is kindly hiding from you - check its Properties.
But:
String path = theFile.getCanonicalPath();
FileReader readMe = new FileReader(path);You don't need all that. Just:
FileReader readMe = new FileReader(theFile);And:
char buffer[] = new char[(int)theFile.length()];You don't need a buffer the size of the file, this is bad practice. Use 8192 or whatever.
while(readData != -1)
readData = readMe.read(buffer);
}That doesn't make sense. Read the data into the buffer and repeat until you get EOF? and do nothing with the contents of the buffer? The canonical read loop in Java goes like this:
while ((count = in.read(buffer)) > 0)
out.write(buffer, 0, count); // or do something else with buffer[0..count-1].
jEditorPane1.setText(String.valueOf(buffer));Bzzt. That won't give you the content of 'buffer'. Use new String(buffer, 0, count) at least. -
Problem sending a null char in an ibwrt buffer?
Has anyone had a problem with sending a null char with ibwrt in NI-488.2
v1.6 on PCI-GPIB card? If so, was there a solution you could find?
Thanks
w tsengThe ibwrt (C/C++) function has the 3rd param that specifies the length
of the buffer to be sent. So null letters can be sent.
ma
"wt" wrote in message
news:6OVd5.112$[email protected]..
> Has anyone had a problem with sending a null char with ibwrt in NI-488.2
> v1.6 on PCI-GPIB card? If so, was there a solution you could find?
>
> Thanks
> w tseng
>
> -
Inserting blanks into a NOT NULL CHAR column
How do you insert a value of blank/spaces into a NOT NULL CHAR column. Oracle 9i interprets the space as a NULL and the insert fails because the column does not allow NULLS. Thanks in advance.
Hi,
19:07:13 topgun>create table t1(c1 varchar2(10) not null);
Table created.
19:07:33 topgun>insert into t1 values (' ');
1 row created.
19:07:42 topgun>select * from t1;
C1
19:07:46 topgun>select count(*) from t1;
COUNT(*)
1
19:07:53 topgun>select * from V$version;
BANNER
Oracle Database 10g Enterprise Edition Release 10.2.0.4.0 - Prod
PL/SQL Release 10.2.0.4.0 - Production
CORE 10.2.0.4.0 Production
TNS for Linux: Version 10.2.0.4.0 - Production
NLSRTL Version 10.2.0.4.0 - Production- Pavan Kumar N -
"We had difficulty reading this feed. null" Atom feeds no longer work?
Hi - our Audioboo feeds used to work fine when submitting as a podcast (eg http://audioboo.fm/users/4705/boos.atom). It seems like they stopped working recently - maybe in the past couple of days - and just report "We had difficulty reading this feed. null" when you try to submit them.
I'm beginning to suspect that the use of atom rather than rss is the cause. Can anyone confirm?
-JonathanThis feed can be subscribed to manually in iTunes (from the 'Advanced' menu) - actually I'm rather surprised it works because it isn't a valid podcast feed (though it is a valid Atom feed).
It has the iTunes 'declaration' and some itunes tags, although the former is contained in a 'feed' tag whereas it should be a 'rss' tag: there is no 'channel' tag enclosing the podcast data, no 'item' tags enclosing each episode, and no 'enclosure' tags within each episode containing the media URL. I'm not surprised you can't submit it as a podcast, and as I say it's a but surprising that the iTunes application recognizes it.
In order to get it accepted in the iTunes Store you need to create a feed in the correct format: this page contains a sample basic feed so you can see how it should look:
http://www.wilmut.org.uk/pc
If the feed contains the valid iTunes format it can also contain atom tags, which iTunes will ignore. -
Read txt file 1 char @ time cnvrt to uppercase problem
I am trying to get the following 2 problems solved. My input file is below and my output is below along with the code.
Can anyone fix this and explain what I am doing wrong? Thank You in advance!
(1) Any string of two or more blanks symbols is replaced by a single blanks.
(2) All sentences start with an upper case letter.
Input A://DataIn.txt = How me? you good.
Output A://DataOut.txt = H o w m e Y U G O . ��
import java.io.*;
public class NumberFormat
private DataInputStream inputStream = null;
private DataOutputStream outputStream = null;
*(1) Any string of two or more blanks symbols is replaced by a single blanks.
(2) All sentences start with an upper case letter.
public static void main(String[] args) throws java.io.IOException
NumberFormat twoTimer = new NumberFormat();
twoTimer.connectToInputFile();
twoTimer.connectToOutputFile();
twoTimer.readInput();
twoTimer.closeFiles();
System.out.println("Check A:/DataOut.txt Now");
public void connectToInputFile()
String inputFileName = getFileName("Enter input file name: A://DataIn.txt");
try
inputStream =
new DataInputStream(
new FileInputStream(inputFileName));
catch(FileNotFoundException e)
System.out.println("File " + inputFileName
+ " not found.");
System.exit(0);
public void connectToOutputFile()
String outputFileName = getFileName("Enter output file name: A://DataOut.txt");
try
outputStream = new DataOutputStream(
new FileOutputStream(outputFileName));
catch(FileNotFoundException e)
System.out.println("Error opening output file "
+ outputFileName);
System.out.println(e.getMessage());
System.exit(0);
private String getFileName(String prompt)
String fileName = null;
System.out.println(prompt);
fileName = SavitchIn.readLineWord();
return fileName;
//===========================================================================
public void readInput()
char prevChar = ' ';
try
char nextChar;
String result = "";
boolean done1 = false;
boolean done2 = false;
char next;
do
next = (char) (inputStream.read()); // <== Read input 1 Character @ time
if (next == '\n')
done1 = true;
if (next == ' ' && next == prevChar)
prevChar = next;
else
if (next == '.' || next == '!' || next == '?')// <== Capitalize next input Character
do
next = ' ';
outputStream.writeChar(next);
next = (char) (inputStream.read());
if (next == '\n')
done2 = true;
next = (char) (inputStream.read());
// next = (char) (inputStream.readNonwhiteChar()); ?????????????
if (next == '\n')// <== never gets to end of file
done2 = true;
outputStream.writeChar(Character.toUpperCase (next));
prevChar = next;
while (!done2);
else
outputStream.writeChar(next);
prevChar = next;
while (!done1);
catch(EOFException e)
//Do nothing. This just ends the loop.
System.out.println("Do Nothing Here");
catch(IOException e)
System.out.println(
"Error: reading or writing files.");
System.out.println(e.getMessage());
System.exit(0);
public void closeFiles()
try
inputStream.close();
outputStream.close();
catch(IOException e)
System.out.println("Error closing files "
+ e.getMessage());
System.exit(0);This line looks fishy:
if (next == ' ' && next == prevChar)
prevChar = next;Try:
if (next == ' ' && next == prevChar)
next = "";That should take care of the extra blanks, though I didn't test it myself, and could very well be wrong.
Not sure about the uppercase, though I imagine it must be reading the ToUpperCase every time after the first period. -
Reading Numeric UDF null value in DI
We have a UDF of Numeric(4) that can be NULL, 0, 1, 2, etc. We try to read it from DI, and if it is NULL, then set the result to be -1 (the default value we difined), so we can differentiate NULL and 0.
The C# code we have look like this:
int LineNumber = -1;
SAPbobsCOM.Company oCompany;
// Code to get Company
SAPbobsCOM.Documents oDoc = oCompany.GetBusinessObject(BoObjectTypes.oQuotations);
oDoc.GetByKey(100); // Get the document by DocEntry
LineNumber = (int)oDoc.UserFields.Fields.Item("U_XX_LN").Value;
The problem is LineNumber gets 0 even if in the database U_XX_LN is NULL. We tried the code below and got the same result because oDoc.UserFields.Fields.Item("U_XX_LN").Value.ToString() always return '0' if it is NULL.
if (string.IsNullOrEmpty(oDoc.UserFields.Fields.Item("U_XX_LN").Value.ToString()))
LineNumber = -1;
else
LineNumber = (int)oDoc.UserFields.Fields.Item("U_XX_LN").Value;
The question is: how can we set it to default -1 if in the database the value is NULL?
Thank you,
GraceHi Grace,
Unfortunately the DI API automatically converts database null values to a default value for the datatype (eg null for numeric becomes 0 and null for strings is an empty string). If you want to differentiate between null and zero you will need to query the table using the isnull command rather than reading the table through the UserTables object:
oRecordSet.DoQuery("select isnull(U_XX_LN, -1) as U_XX_LN from [@MYTABLE] where Code = 'MYCODE')
This will convert the null value to a -1 in the recordset so you can tell the difference between nulls and zeros.
Kind Regards,
Owen -
Reading lines beyon null lines in a file
While writing a file-processing script, I came across the following case where I need
to read info like ENDDOC and PGCount for multiple records that are in the same file.
; Record 1
@C ENDDOC# ATYC-12769314
@C PGCount 20
@T ATYC-12769295
; Record 2
@C ENDDOC# ATYC-12769317
@C PGCount 3
@T ATYC-12769315
Can you suggest how should I read the lines beyond null line in between?There is no null line in there. There's only a line that consists of the empty string (assuming you are using readLine()).
Please not that those two variables will have different values:
String emptyString = "";
String nullString=null;readLine() will return the value of emptyString if it reads a line that hasn't got any characters on it and the value of nullString if it reaches the end of file. -
Reading attachment: diposition NULL
Hi,
I am trying to read attachment using javamail but when I use getDisposition function, I always get NULL disposition value,even for attachment.Please help me.This is the code I am using.
import java.io.*;
import javax.swing.*;
import java.util.*;
import java.util.Properties;
import javax.mail.*;
import javax.mail.internet.*;
import java.sql.*;
public class try_attachment{
public static void main(String args[])throws Exception
String host = "host";
String username = "username";
String password = "password";
Properties Prop = new Properties();
Session session = Session.getInstance(Prop,null);
Store store = session.getStore("imap");
store.connect(host,username,password);
// open Inbox
Folder folder = store.getFolder("INBOX");
folder.open(Folder.READ_WRITE);
// get Directory
Message msg[] = folder.getMessages();
for (int i=0;i<msg.length;i++)
Object content = msg.getContent();
if(content instanceof Multipart)
handleMultipart(( Multipart)content);
else
handlePart(msg[i]);
folder.close(false);
store.close();
public static void handleMultipart( Multipart multipart)
throws MessagingException, IOException
for(int i=0;i<multipart.getCount();i++)
handlePart(multipart.getBodyPart(i));
public static void handlePart(Part part)throws MessagingException,IOException
String disposition = part.getDisposition();
String contentType = part.getContentType();
// trying to read disposition value
System.out.println("Hello "+ disposition);
try{ if (disposition == null)
System.out.println("Null: " +contentType);
//checkif plain
// if ((contentType.length()>=10)&& (contentType.toLowerCase().substring(0,10).equals("text/plain")))
// part.writeTo(System.out);
else if(disposition.equalsIgnoreCase(Part.ATTACHMENT))
System.out.println("Attachment:" + part.getFileName() + ":" + contentType);
saveFile(part.getFileName(),part.getInputStream());
else if(disposition.equalsIgnoreCase(Part.INLINE))
System.out.println("Inline :"+ part.getFileName()+":" + contentType);
saveFile(part.getFileName(),part.getInputStream());
else
System.out.println("Other");
catch(Exception e)
{ System.out.println(e);}
public static void saveFile(String filename, InputStream input) throws IOException
if (filename == null)
filename = File.createTempFile("testmail",".out").getName();
//do not overwrite
File file = new File(filename);
for(int i=0;file.exists();i++)
file = new File(filename+i);
FileOutputStream fos = new FileOutputStream(file);
BufferedOutputStream bos = new BufferedOutputStream(fos);
BufferedInputStream bis = new BufferedInputStream(input);
int aByte;
while ((aByte = bis.read())!= -1)
bos.write(aByte);
bos.flush();
bos.close();
bis.close();Hello Mark,
1. My Soap Sender Adapter, I checked the Keep Attachment option
2. I am getting the WSDL file from the SOAP Sender Agreement.. it is like http(s)://host:port/XISOAPAdapter/MessageServlet?channel=p:s:c? as you said.
I used the user-defined function, it works when <inc:Include href="cid:test.jpg" xmlns:inc="http://www.w3.org/2004/08/xop/include" /> is deleted in the message.
If the coming message includes <inc:Include href="cid:test.jpg" xmlns:inc="http://www.w3.org/2004/08/xop/include" />,
the <null> error occurs.
Thanx for your reply.. -
GroupSpace RSS Reader Portlet Bug - Null Titles
I have a GroupSpace community that utilizes the out-of-box GS RSS Reader portlet. Currently, I am encountering an issue with displayed feed channels/entries: the titles are null. In the tree view (the left pane), the titles for entries are blank. I can click on the icons to navigate the tree. In the details view (the right pane), titles are displayed as "null" and authors are blank. I cannot click on the titles to view the channel/entry.
I checked the content repository in the the WebLogic Portal Admin Console and the titles are displayed correctly there. I didn't notice anything in the server logs, not sure what else I could check.They are all RSS 2.0, which is supported. And yes, all the entries and channels have titles. They just don't show up in the list in the "Title" column or in the tree view. I did notice that the title does appear correctly in header section of the details view though.
Other RSS Readers display the feeds/channels properly. Several months (5+) ago, this portlet was displaying them correctly. I'm not sure what changed. I don't think the code to display the portlet has changed. There have been many changes to other portlets in the portal, but the portlet resides on its own page so I'm not sure what could be interfering with it. I did have to modify the groupspace callback class to address an issue with communities not being added to the database with dvt enabled.
I'm certain the the portlet is consuming the XML files correctly as I can see the content in the WLP content repository.
Edited by: TNgo on May 12, 2010 1:20 PM -
Null chars in strings with longer than 4000
Here's the situation:
I'm retrieving a large string (~10,000 characters) from a view
in oracle 8, using a VB app and an ODBC connecion. The string is
datatype long. When I get the string and analyze it in my
program, I find that ASCII 0 (null) has been inserted at
location 4000. I verified that the string was actually not
stored with this null in Oracle, so I figure the problem is
something with ADO or VB. Here is how I'm retrieving the
string...
'rs is my recordset
sString = rs("LONG_STRING")
Any thoughts on what the problem is here? Thanks.
--FrankI found a solution that appears to work. I switched my DSN so
I'm using the "Mircosoft ODBC for Oracle" driver as opposed to
the "Oracle ODBC Driver". Now the LONG text fields are returned
as I expected.
--Frank -
GUI to set file, other class to read it, file null error
Perhaps not the most informative subject for this problem. I have a GUI in which a file chooser is used to select a file to be read. Another class reads in this file, and goes on to process it. My main class sets up the GUI and then goes on to process the files in the second class.
I am having trouble, I believe, with timing. The main class sets up the GUI, it runs perfectly, and then I catch a problem (that will evolve into an error), where the file I am supposed to process is null, because I have not had a chance to use the file chooser in the GUI. I haven't had any luck finding a solution online, although if there is one (or another tutorial I missed), please feel free to pass the link(s) along. I am posting the relevant code below.
Thanks,
Danielle
public Main()
* @param args the command line arguments
public static void main(String[] args)
javax.swing.SwingUtilities.invokeLater(new Runnable()
public void run()
System.out.println("About to run create GUI method");
MGui app = new MGui();
System.out.println("declared a new MGui....");
app.createAndShowGUI();
/**Starting to get file choices and moving them into GPR Handler:
GprHandler gpr = new GprHandler();
//~ System.out.println("should be perfect????");
// }//end if
}// end main(String[] args)
}// end class MainThe GUI uses the following code for the file chooser:
private class enterFile2Action implements ActionListener
public void actionPerformed(ActionEvent evt)
JFileChooser chooser = new JFileChooser();
int rVal = chooser.showOpenDialog(enterFile1);
if(rVal == JFileChooser.APPROVE_OPTION)
inputFile2 = chooser.getSelectedFile();
PrintWriter outputStream;
file2Name = inputFile2.getName();
enterLabel2.setText(file2Name);
}Finally, the GprHandler class processes the file- reading it and such. The only relevant method, however is below.
/** taking in files*/
public boolean readFiles()
boolean nullFiles = true;
System.out.println("into method readFiles()");
if (MGui.get1Name() != null)
System.out.println("name isn't null");
file1Name = MGui.get1Name();
file1 = new File(file1Name);
if (MGui.get2Name() != null)
file2Name = MGui.get2Name();
file2 = new File(file2Name);
nullFiles = false;
}//end if
if (nullFiles)
System.out.println("one or more files is undeclared");
return false;
}//end if
else
try{
file1Reader = new FileReader(file1);
file2Reader = new FileReader(file2);
}//end try
catch (FileNotFoundException e)
System.out.println("file not found exception");
return false;
} //end catch
}//end else
return true;
}No, you're quite right. I want the GprHandler to
start when I've got something there for it to start
with. I never thought to call it from the
actionPerformed though. I think I've been listening
to too many lectures on some prof's definition of a
"proper main class".
I think I understand what you're suggesting: I
should simply remove the GprHandler part from my main
class and place it instead in the actionPerformed
methods, once the files are actually named/chosen.
Did I get that right?
Qualified yes. Does GPRHandler implement Runnable? I mean you don't want to do the processing in the swing event thread. So what you should do is in the actionPerformed create the Handler (with the file or whatever other bits it needs) and then start it.
Then it can process merrily along in a seperate thread. -
Hello,
I'm just trying to read the ACLs of some portal ressources. I found some threads that describe exactly what I want to do. But all this threads are resolved and it seems, nobody gets the same error. Following, there is my code. A little shortened without try/catches. The Problem is, that I get a NullPointerException in the Line
"IResourceAclEntryList acllist = acl.getEntries();" this means to me, that I get the IResourceAclManager, but I don't get any ACLs. Has anybody a clue, why I don't get an ACLs?
Best regards,
Christian
com.sap.security.api.IUser sapUser = request.getUser();
com.sapportals.portal.security.usermanagement.IUser ep5User = null;
ep5User = com.sapportals.wcm.util.usermanagement.WPUMFactory.getUserFactory().getEP5User(sapUser);
ResourceContext context = new ResourceContext(ep5User);
RID rid = RID.getRID("/documents");
IResourceFactory factory = ResourceFactory.getInstance();
ICollection folder = (ICollection) factory.getResource(rid, context);
ArrayList al = new ArrayList();
IResourceListIterator it = folder.getChildren().listIterator();
if (it != null) {
while (it.hasNext()) {
IResource res = it.next();
String name = res.getName();
String rawRid = res.getRID().toString();
boolean isFolder = res.isCollection();
response.write(name);
IResourceFactory resFactory = ResourceFactory.getInstance();
IRepositoryServiceFactory repServiceFactory = resFactory.getServiceFactory();
IAclService aclService =
(IAclService) repServiceFactory.getRepositoryService(res, "ServiceAclRepositoryService");
IResourceAclManager aclMgr = aclService.getAclManager();
IResourceAcl acl = aclMgr.getAcl(res);
if (acl == null) {
response.write("ACL = NULL");
acl = aclMgr.getInheritedAcl(res);
IResourceAclEntryList acllist = acl.getEntries();
IResourceAclEntryListIterator listIt = acllist.iterator();Hi
Try with this code ...
ISecurityManager sm = res.getRepositoryManager().getSecurityManager(res);
if (sm != null && sm instanceof IAclSecurityManager) {
IAclSecurityManager asm = (IAclSecurityManager) sm;
IResourceAclManager ram = asm.getAclManager();
IResourceAcl ra = ram.getAcl(res);
if (ra == null) {
response.write("ACL = NULL");
ra = ram.getInheritedAcl(res);
IResourceAclEntryList rel = ra.getEntries();
Check this message also Re: Read foder permissions
Regards
BP -
Mysterious file in trash containing null chars
in my trash appears a mysterious file. ive made some screenshots of it:
http://home.arcor.de/matthiascando/images/finderError1.png
http://home.arcor.de/matthiascando/images/finderError2.png
it resists any attempts to empty the trash. when i click on it, it disappers only to show up some seconds later again.
i did a rm -rf ~/.Trash - no result. with ls -al ~/.Trash/ it doesnt appear in the terminal.
i tried to create a new account but after a while (a day or so) the file is there again.
has anybody an idea what to do or some experience?Do you happen to have "show hidden files" enabled? I once had the same problem- a file continually appeared on my desktop and right after deleting it, it would reappear. I then remembered that I had used Onyx to show me hidden files during the installation of some software, and I had never hid them again. That may be one of those hidden files.
-
How to read more than 132 char using Read_Text Fn. Module
Hi,
I am using Fn. Module <b>Read_Text</b> in my program, but the fn. module is only retrieving 132char data and remaining data is getting truncated. In my case Text size is more than 132char...pls, let me Know, how can i get entire text or i have to use any other Fn. ModuleHi,
In READ_TEXT function module, TLINE structure has the component TDLINE with 132 characters. So, u can't read more than 132 characters. If u want to read more than that, u have to write FM of ur own which can read more than 132 characters.
Maybe you are looking for
-
Hi Gurus, Hope you can help me with this issue. On the f110, I encountered error 006, no payment method exists. When I checked the detailed log, it says that: Our bank XXX is being checked No Amount has been scheduled for currency XXX and at least 00
-
Create materialized view failed!
I want to create a mv from a table which does not contain primary key constraint,but failed. why? SQL> Create Table tb_test01 2 ( 3 Id Number, 4 Name Varchar2(1024) 5 ); Table created. SQL> SQL> Create Materialized View Log On tb_test01 2 With Sequen
-
Hi, I was very excited to see webgl support but on inspection of the code exported an very upset. I can no longer write code in an external editor and target the movieclips from Flash. So what worked for the Canvas version does not work for the webgl
-
I'm GLAD I DID NOT INSTALL THIS AMP what a headache
WOW am I glad I read the forums befor I downloaded this JUNK of a player. To many people with to many problems to use this sorry AMP!! You can't even uninstall it and it wants to load up at start up. The softwear for the AMP should be in the add/remo
-
Do I need to pay for Cover art?
Hello All, Still new to Mac and iTunes. Please forgive me in case this is obvious question. I have imported several CDs through iTunes with no issues. However, the cover art will not download unless I have an iTune account. So I made one. But, I did