Reputation: 505
I am new to Java and I was wondering if there was a way in which I can limit the number of characters entered in a String?
I have to create an application for a school project in which I need to use files for storing data and my class has various string variables and since I need to use the seek method of the RandomAccessFile class, and also to read only one object at a time from the file, I need all objects to have the same size, so is it possible?
Upvotes: 0
Views: 2850
Reputation: 38328
The description of your class project sounds like you need or want to use a fixed length record structure. These are not nicely supported in Java.
If you have one field in your record, then just use a solution similar to that described in the Julian answer. Instead of worrying about short fields, just append spaces at the end and trim to field length.
If you have multiple fields in your record then you will want to do something like this:
Create a class that has a field for each field in your record. String
is the most likely type for each field.
Add a method to the class (mentioned in #1) to build the fixed length record. This method will do the following for each field in the fixed length record:
This assumes that all fields are left justified and space filled.
Upvotes: 0
Reputation: 96
You cannot limit the number of characters in a String.
I think,
in your usecase,
the best solution would be to trim the string to the maximum size.
For Example:
String input = "123456789";
String result = input.substring(0, 4);
//result is: "1234"
To ensure that you do not receive an IndexOutOfBoundsException
when the input string
is less than the expected length do the following instead:
input.substring(0, Math.min(MAX_CHAR, input.length()));
Math.min()
will return the minimum of the two parameters.
Upvotes: 2
Reputation: 24770
When reading data from a file, it would make sense to read your data as a byte[]
, which obviously has a fixed size.
Converting a byte[]
to a String
is as easy as new String(bytes, StandardCharsets.UTF8)
or any other encoding.
That being said, you could make the encoding configurable in your application, or use the system-default. In that case, you can just new String(bytes)
to convert them.
You should be aware though that the size of a String
does not always match its size in bytes. In fact for a simple encoding such as US_ASCII
or ISO_8859_1
(=Latin1) it's just 1 byte per character. However, an encoding like UTF-8
supports more characters, and will sometimes need multiple bytes to store a single character.
That challenge of encodings and their variable character-size has been around for ages and is the reason why databases have a variety of different datatypes for strings (e.g. VARCHAR
vs NVARCHAR
).
Upvotes: 0