Converting array string to string and back in Java - java

I have an array String[] in Java, and must first encode/convert it into a String and then further in the code covert it back to the String[] array. The thing is that I can have any character in a string in String[] array so I must be very careful when encoding. And all the information necessary to decode it must be in the final string. I can not return a string and some other information in an extra variable.
My algorithm I have devised so far is to:
Append all the strings next to each other, for example like this:
String[] a = {"lala", "exe", "a"}
into
String b = "lalaexea"
Append at the end of the string the lengths of all the strings from String[], separated from the main text by $ sign and then each length separated by a comma, so:
b = "lalaexea$4,3,1"
Then when converting it back, I would first read the lengths from behind and then based on them, the real strings.
But maybe there is an easier way?
Cheers!

If you don't wanna spend so much time with string operations you could use java serialization + commons codecs like this:
public void stringArrayTest() throws IOException, ClassNotFoundException, DecoderException {
String[] strs = new String[] {"test 1", "test 2", "test 3"};
System.out.println(Arrays.toString(strs));
// serialize
ByteArrayOutputStream out = new ByteArrayOutputStream();
new ObjectOutputStream(out).writeObject(strs);
// your string
String yourString = new String(Hex.encodeHex(out.toByteArray()));
System.out.println(yourString);
// deserialize
ByteArrayInputStream in = new ByteArrayInputStream(Hex.decodeHex(yourString.toCharArray()));
System.out.println(Arrays.toString((String[]) new ObjectInputStream(in).readObject()));
}
This will return the following output:
[test 1, test 2, test 3]
aced0005757200135b4c6a6176612e6c616e672e537472696e673badd256e7e91d7b47020000787000000003740006746573742031740006746573742032740006746573742033
[test 1, test 2, test 3]
If you are using maven, you can use the following dependency for commons codec:
<dependency>
<groupId>commons-codec</groupId>
<artifactId>commons-codec</artifactId>
<version>1.2</version>
</dependency>
As suggested with base64 (two lines change):
String yourString = new String(Base64.encodeBase64(out.toByteArray()));
ByteArrayInputStream in = new ByteArrayInputStream(Base64.decodeBase64(yourString.getBytes()));
In case of Base64 the result string is shorter, for the code exposed below:
[test 1, test 2, test 3]
rO0ABXVyABNbTGphdmEubGFuZy5TdHJpbmc7rdJW5+kde0cCAAB4cAAAAAN0AAZ0ZXN0IDF0AAZ0ZXN0IDJ0AAZ0ZXN0IDM=
[test 1, test 2, test 3]
Regarding the times for each approach, I perform 10^5 executions of each method and the result was as follows:
String manipulation: 156 ms
Hex: 376 ms
Base64: 379 ms
Code used for test:
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.util.StringTokenizer;
import org.apache.commons.codec.DecoderException;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.codec.binary.Hex;
public class StringArrayRepresentationTest {
public static void main(String[] args) throws IOException, ClassNotFoundException, DecoderException {
String[] strs = new String[] {"test 1", "test 2", "test 3"};
long t = System.currentTimeMillis();
for (int i =0; i < 100000;i++) {
stringManipulation(strs);
}
System.out.println("String manipulation: " + (System.currentTimeMillis() - t));
t = System.currentTimeMillis();
for (int i =0; i < 100000;i++) {
testHex(strs);
}
System.out.println("Hex: " + (System.currentTimeMillis() - t));
t = System.currentTimeMillis();
for (int i =0; i < 100000;i++) {
testBase64(strs);
}
System.out.println("Base64: " + (System.currentTimeMillis() - t));
}
public static void stringManipulation(String[] strs) {
String result = serialize(strs);
unserialize(result);
}
private static String[] unserialize(String result) {
int sizesSplitPoint = result.toString().lastIndexOf('$');
String sizes = result.substring(sizesSplitPoint+1);
StringTokenizer st = new StringTokenizer(sizes, ";");
String[] resultArray = new String[st.countTokens()];
int i = 0;
int lastPosition = 0;
while (st.hasMoreTokens()) {
String stringLengthStr = st.nextToken();
int stringLength = Integer.parseInt(stringLengthStr);
resultArray[i++] = result.substring(lastPosition, lastPosition + stringLength);
lastPosition += stringLength;
}
return resultArray;
}
private static String serialize(String[] strs) {
StringBuilder sizes = new StringBuilder("$");
StringBuilder result = new StringBuilder();
for (String str : strs) {
if (sizes.length() != 1) {
sizes.append(';');
}
sizes.append(str.length());
result.append(str);
}
result.append(sizes.toString());
return result.toString();
}
public static void testBase64(String[] strs) throws IOException, ClassNotFoundException, DecoderException {
// serialize
ByteArrayOutputStream out = new ByteArrayOutputStream();
new ObjectOutputStream(out).writeObject(strs);
// your string
String yourString = new String(Base64.encodeBase64(out.toByteArray()));
// deserialize
ByteArrayInputStream in = new ByteArrayInputStream(Base64.decodeBase64(yourString.getBytes()));
}
public static void testHex(String[] strs) throws IOException, ClassNotFoundException, DecoderException {
// serialize
ByteArrayOutputStream out = new ByteArrayOutputStream();
new ObjectOutputStream(out).writeObject(strs);
// your string
String yourString = new String(Hex.encodeHex(out.toByteArray()));
// deserialize
ByteArrayInputStream in = new ByteArrayInputStream(Hex.decodeHex(yourString.toCharArray()));
}
}

Use a Json parser like Jackson to serialize/deserialize other type of objects as well like integer/floats ext to strings and back.

Just use a known separator (such as # or # to append your strings), then use yourString.split(yourSeparator) to get an array from it.

I would use the symbol between the words to later use the String#split method to get the String back. Based in your $ symbol example, it would be
public String mergeStrings(String[] ss) {
StringBuilder sb = new StringBuilder();
for(String s : ss) {
sb.append(s);
sb.append('$');
}
return sb.toString();
}
public String[] unmergeStrings(String s) {
return s.split("\\$");
}
Note that in this example, I add a double \ before the $ symbol because the String#split method receives a regular expression as parameter, and the $ symbol is a special character in regex.
public String processData(String[] ss) {
String mergedString = mergeStrings(ss);
//process data...
//a little example...
for(int i = 0; i < mergedString.length(); i++) {
if (mergedString.charAt(i) == '$') {
System.out.println();
} else {
System.out.print(mergedString.charAt(i));
}
}
System.out.println();
//unmerging the data again
String[] oldData = unmergeStrings(mergedString);
}
In order to support any character in your String[], it would be better to set not a single character as separator but instead another String. The methods would turn into this:
public static final String STRING_SEPARATOR = "#|$|#";
public static final String STRING_SEPARATOR_REGEX = "#\\|\\$\\|#";
public String mergeStrings(String[] ss) {
StringBuilder sb = new StringBuilder();
for(String s : ss) {
sb.append(s);
sb.append(STRING_SEPARATOR);
}
return sb.toString();
}
public String[] unmergeStrings(String s) {
return s.split(STRING_SEPARATOR_REGEX);
}

Related

Find string inside of the text file. Then getting the following line and need to Split by Index of and substring

Find string inside of a text file. Then get the following line and split by indexOf() and substring().
import java.util.*;
import java.io.*;
public class FileReadTest {
public static void main(String[] args) throws IOException {
File f = new File("a.dat");
Scanner fin = new Scanner(f);
String airportcode = "HOI";
while (fin.hasNextLine()) {
String line = fin.nextLine();
int firstindex = line.indexOf(airportcode);
if (firstindex > 0) {
int Code = line.indexOf("|");
int Country = line.lastIndexOf("|",Code);
int State = line.indexOf("|", Country);
int City = line.indexOf("|", State);
int Airport = line.indexOf("|", City);
System.out.println(Code);
System.out.println(Country);
System.out.println(State);
System.out.println(City);
System.out.println(Airport);
System.out.println(line.substring(0, Code));
break;
}
}
fin.close();
}
}
The 1 sout looks like this:
French Polynesia|HOI|Hao|Tuamotos|Hao Airport
I need using only indexOf() and substring(),
but I need it like this:
French Polynesia
HOI
Hao
Tuamotos
Hao Airport
What should I do?
Starting from the assumption you always the same number of fields, in your case 5 separated by the character | you can solve the problem without using String split method but just indexOf and substring like below:
String s = "French Polynesia|HOI|Hao|Tuamotos|Hao Airport";
for (int i = 0; i < 4; ++i) {
int endIndex = s.indexOf("|");
System.out.println(s.substring(0, endIndex));
s = s.substring(endIndex + 1);
}
System.out.println(s);
The code will print all the fields that can be assigned to your distinct variables.
Assuming that:
file content has lines with the following structure: French Polynesia|HOI|Hao|Tuamotos|Hao Airport
you need to print only those lines that contain "HOI" string
you have to use indexOf and substring only.
Here is code snippet that should work for you (file a.dat is located in resources folder):
package example;
import java.util.*; // for Scanner
import java.io.*; // for File and IOException
public class FileReadTest {
public static void main(String[] args) throws IOException {
File f = new File(
Objects.requireNonNull(FileReadTest.class.getClassLoader().getResource("a.dat")).getFile()
);
Scanner fin = new Scanner(f);
String airportcode = "HOI";
while (fin.hasNextLine()) {
String line = fin.nextLine();
if (line.indexOf(airportcode) != -1) {
int firstindex;
while ((firstindex = line.indexOf("|")) != -1) {
System.out.println(line.substring(0, firstindex));
line = line.substring(firstindex + 1);
}
System.out.println(line); // last data
}
}
}
}

Java,problems with decrypting file

My code doesn't work correctly, I'm trying to decrypt a message but instead I get something like , 0, 3, ,, , 5, 7, <, ;, , ;, 9, ,, (, 4, , , -, ,, ), (, , �, ￸]
Please help me find where am I am wrong:
public class WorkInFile {
public static void main(String[] args) throws IOException {
FileInputStream encoded=new FileInputStream("C://Games//encoded.txt");//contains ƪÄÖØÐîÃÜÙäÌÊÛÓÕÒáÄßÕÍǨ³¾êÉàÝâÝãƒâÝäìÚÇäÖçÅáâÄÄÌØÐƭèÑØǑÚÚŲã¨
FileInputStream coded = new FileInputStream("C://Games//code.txt");//contains icbakwtbxxvcelsmjpbochqlltowxhlhvhyywsyqraargpdsycikmgeakonpiwcqmofwms
String text = encoded.toString();
String text2=coded.toString();
char[] chars=text.toCharArray();
char[] chars2=text2.toCharArray();
int index=0;
char[] res=new char[text.length()];
for (char aChar : chars) {
for (char c : chars2) {
res[index] = (char) (aChar - c);
}
index++;
}
String result= Arrays.toString(res);
System.out.println(result);
}
}
Files.readAllBytes(Paths.get("file-path"))
Java now offers a beautiful one-liner for reading file content.
Here is the working code for fetching file content as a string:
// WorkInFile.java
import java.nio.file.*;
public class WorkInFile {
public static void main(String[] args) {
try {
String text = new String(Files.readAllBytes(Paths.get("encoded.txt")));
System.out.println("Encoded.txt = " + text);
String text2 = new String(Files.readAllBytes(Paths.get("code.txt")));
System.out.println("code.txt = " + text2);
} catch (Exception ex) {
System.out.println(ex.toString());
}
}
}
If the expected message is in Japanese and it talks about Soviet data, this code is for you.
You must use a BufferedReader for read the file and a StringBuilder for build a String with what the BufferedReader extracts from the file.
public static void main(String args[]) {
String text;
String text2;
try {
Path encodedPath = Paths.get("C://Games//encoded.txt");
File encodedFile = new File(String.valueOf(encodedPath));
Path codedPath = Paths.get("C://Games//code.txt");
File codedFile = new File(String.valueOf(codedPath));
StringBuilder codedBuilder = new StringBuilder();
StringBuilder encodedBuilder = new StringBuilder();
try (
FileInputStream encoded = new FileInputStream(encodedFile.getAbsolutePath());
FileInputStream coded = new FileInputStream(codedFile.getAbsolutePath())
) {
try (BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(coded))) {
String line;
while ((line = bufferedReader.readLine()) != null){
codedBuilder.append(line);
}
text = codedBuilder.toString();
}
try (BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(encoded))){
String line;
while ((line = bufferedReader.readLine()) != null){
encodedBuilder.append(line);
}
text2 = encodedBuilder.toString();
}
char[] chars = text.toCharArray();
char[] chars2 = text2.toCharArray();
int index = 0;
char[] res = new char[text.length()];
for (char aChar : chars) {
for (char c : chars2) {
res[index] = (char) (aChar - c);
}
index++;
}
String result = Arrays.toString(res);
System.out.println(result);
}
}
catch (IOException e) {
e.printStackTrace();
}
}
Let me know if that's what you wanted !
I think your problem lies out here:
String text = encoded.toString();
String text2=coded.toString();
You may refer to documentation to reach out that:
public String toString()
Returns a string representation of the object. In general, the toString method returns a string that "textually represents" this object. The result should be a concise but informative representation that is easy for a person to read. It is recommended that all subclasses override this method.
The toString method for class Object returns a string consisting of the name of the class of which the object is an instance, the at-sign character `#', and the unsigned hexadecimal representation of the hash code of the object. In other words, this method returns a string equal to the value of:
getClass().getName() + '#' + Integer.toHexString(hashCode())
Returns:
a string representation of the object.
So, toString() returns the representation of FileInputStream not the content of the stream.

Reading character files between specific word in java

I have a java file, FileJava.java like this:
public class FileJava {
public static void main(String args[]) {
for (int i = 0; i < 5; i++) {
}
}
}
Then, i read above code line by line using this code:
import java.util.List;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.util.ArrayList;
public class FileReplace {
List<String> lines = new ArrayList<String>();
String line = null;
public void doIt() {
try {
File f1 = new File("FileJava.java");
FileReader fr = new FileReader(f1);
BufferedReader br = new BufferedReader(fr);
while ((line = br.readLine()) != null) {
if (line.contains("for"))
{
lines.add("long A=0;");
if(line.contains("(") && line.contains(")")){
String get = line;
String[] split = get.split(";");
String s1 = split[0];
String s2 = split[1];
String s3 = split[2];
}
}
lines.add(line);
}
fr.close();
br.close();
FileWriter fw = new FileWriter(f1);
BufferedWriter out = new BufferedWriter(fw);
for(String s : lines)
out.write(s);
out.flush();
out.close();
} catch (Exception ex) {
ex.printStackTrace();
}
}
public static void main(String args[]) {
FileReplace fr = new FileReplace();
fr.doIt();
}
}
The question is, how to read character between '(' and ')' inside (for) in the FileJava.java, the character i mean "int i = 0; i < 5; i++" that will be stored in a variable, i have split based on ";", but when i print, the value :
s1 = for (int i = 0
s2 = i < 5
s3 = i++) {
While i expect:
s1 = int i = 0
s2 = i < 5
s3 = i++
Thanks
To answer your question how to restrict the splitting to the parenthesized section:
String[] split =
get.substring( get.indexOf('(')+1, get.indexOf(')').split("\\s*;\\s*");
Edit to address another prob.
Printing of the file will all happen in one line, because BufferedReader.readLine strips the line ends (LF, CRLF) from the line it returns. Thus, add a line break when writing:
for(String s : lines){
out.write(s);
out.newLine();
}
int index1 = line.indexOf("(");
int index2 = line.indexOf(")");
line = line.subString(index1 + 1, index2);
Its because you are splitting on ';' for the input
for (int i = 0; i < 5; i++) {
which will return all the characters between ';'
You can write a new method, called getBracketContent for example, that will be something like
String getBracketContent(String str)
{
int startIdx = str.indexOf('(')
int endIdx = str.indexOf(')')
String content = str.subString(startIdx + 1, endIdx);
}
then your code would be
if(line.contains("(") && line.contains(")")){
String get = getBracketContent(line);
String[] split = get.split(";");
Ideally I would use regular expressions to parse the information you need, but that is probably something you may want to look into later.
If you want to read the contents of a java file, you would be much better off using an AST (Abstract Syntax Tree) parser which will read in the contents of the file and then callback when it encounters certain expressions. In your case, you can listen just for the 'for' loop.

How to convert a String array to a Byte array? (java)

I have a one dimensional String array that I want to convert into a one dimensional byte array. How do I do this? Does this require ByteBuffer? How can I do this? (The strings can be any length, just want to know how to go about doing such an act. And after you convert it into a byte array how could I convert it back into a String array?
-Dan
Array to Array you should convert manually with parsing into both sides, but if you have just a String you can String.getBytes() and new String(byte[] data);
like this
public static void main(String[] args) {
String[] strings = new String[]{"first", "second"};
System.out.println(Arrays.toString(strings));
byte[][] byteStrings = convertToBytes(strings);
strings = convertToStrings(byteStrings);
System.out.println(Arrays.toString(strings));
}
private static String[] convertToStrings(byte[][] byteStrings) {
String[] data = new String[byteStrings.length];
for (int i = 0; i < byteStrings.length; i++) {
data[i] = new String(byteStrings[i], Charset.defaultCharset());
}
return data;
}
private static byte[][] convertToBytes(String[] strings) {
byte[][] data = new byte[strings.length][];
for (int i = 0; i < strings.length; i++) {
String string = strings[i];
data[i] = string.getBytes(Charset.defaultCharset()); // you can chose charset
}
return data;
}
for one byte[] from string[] you have to:
to byteArray concat byte arrays from each string using some delimeter
from bytearray split by te same delimiter and create String as I
described above.
You don't say what you want to do with the bytes (aside from convert them back to a String[] afterward), but assuming you can just treat them as an opaque bag of data (so you can save them to a file or send them over the network or whatnot, but you don't need to examine or modify them in any way), I think your best bet is to use serialization. To serialize your string-array, you would write something like:
final String[] stringArray = { "foo", "bar", "baz" };
final ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
final ObjectOutputStream objectOutputStream =
new ObjectOutputStream(byteArrayOutputStream);
objectOutputStream.writeObject(stringArray);
objectOutputStream.flush();
objectOutputStream.close();
final byte[] byteArray = byteArrayOutputStream.toByteArray();
and to recover it afterward, you'd write the reverse:
final ByteArrayInputStream byteArrayInputStream =
new ByteArrayInputStream(byteArray);
final ObjectInputStream objectInputStream =
new ObjectInputStream(byteArrayInputStream);
final String[] stringArray2 = (String[]) objectInputStream.readObject();
objectInputStream.close();
You can check this
package javaapplication2;
import java.util.Arrays;
/**
*
* #author Ali
*/
public class JavaApplication2 {
public static byte[] to_byte(String[] strs) {
byte[] bytes=new byte[strs.length];
for (int i=0; i<strs.length; i++) {
bytes[i]=Byte.parseByte(strs[i]);
}
return bytes;
}
public static void main(String[] args) {
String[] input = {"1","2","3"}; //original data
byte[] byteArray = to_byte(input);//data to byte array
String[] recovered=Arrays.toString( byteArray).split(",");// recovered data
}
}
First declare the string like I declared here str="Suresh"
Second use getBytes() to convert it in bytes
getBytes returns the array of byte.
String str="Suresh";
byte[] s=str.getBytes();
String.getBytes()? is what you're looking for.
I would treat this as a serialization problem and just implemented it as follows(complete and working Java code):
import java.nio.ByteBuffer;
import java.util.ArrayList;
public class Serialization {
public static byte[] serialize(String[] strs) {
ArrayList<Byte> byteList = new ArrayList<Byte>();
for (String str: strs) {
int len = str.getBytes().length;
ByteBuffer bb = ByteBuffer.allocate(4);
bb.putInt(len);
byte[] lenArray = bb.array();
for (byte b: lenArray) {
byteList.add(b);
}
byte[] strArray = str.getBytes();
for (byte b: strArray) {
byteList.add(b);
}
}
byte[] result = new byte[byteList.size()];
for (int i=0; i<byteList.size(); i++) {
result[i] = byteList.get(i);
}
return result;
}
public static String[] unserialize(byte[] bytes) {
ArrayList<String> strList = new ArrayList<String>();
for (int i=0; i< bytes.length;) {
byte[] lenArray = new byte[4];
for (int j=i; j<i+4; j++) {
lenArray[j-i] = bytes[j];
}
ByteBuffer wrapped = ByteBuffer.wrap(lenArray);
int len = wrapped.getInt();
byte[] strArray = new byte[len];
for (int k=i+4; k<i+4+len; k++) {
strArray[k-i-4] = bytes[k];
}
strList.add(new String(strArray));
i += 4+len;
}
return strList.toArray(new String[strList.size()]);
}
public static void main(String[] args) {
String[] input = {"This is","a serialization problem;","string concatenation will do as well","in some cases."};
byte[] byteArray = serialize(input);
String[] output = unserialize(byteArray);
for (String str: output) {
System.out.println(str);
}
}
}
The idea is that in the resulting byte array we store the length of the first string(which is always 4 bytes if we use the type int), followed by the bytes of the first string(whose length can be read later from the preceding 4 bytes), then followed by the length of the second string and the bytes of the second string, and so on. This way, the string array can be recovered easily from the resulting byte array, as demonstrated by the code above. And this serialization approach can handle any situation.
And the code can be much simpler if we make an assumption to the input string array:
public class Concatenation {
public static byte[] concatenate(String[] strs) {
StringBuilder sb = new StringBuilder();
for (int i=0; i<strs.length; i++) {
sb.append(strs[i]);
if (i != strs.length-1) {
sb.append("*.*"); //concatenate by this splitter
}
}
return sb.toString().getBytes();
}
public static String[] split(byte[] bytes) {
String entire = new String(bytes);
return entire.split("\\*\\.\\*");
}
public static void main(String[] args) {
String[] input = {"This is","a serialization problem;","string concatenation will do as well","in some cases."};
byte[] byteArray = concatenate(input);
String[] output = split(byteArray);
for (String str: output) {
System.out.println(str);
}
}
}
The assumption is that *.* does not exist in any string from the input array. In other words, if you know in advance some special sequence of symbols won't appear in any string of the input array, you may use that sequence as the splitter.
You can iterate for each string and keep appending to the final byte array.
String example = "This is an example";
//Convert String to byte[] using .getBytes() function
byte[] bytes = example.getBytes();
//Convert byte[] to String using new String(byte[])
String s = new String(bytes);

The first element discarded while sorting text file using arrays in java

I have this code to sort a text file using arrays in java, but it always discard the first line of the text while sorting.
Here is my code:
import java.io.*;
public class Main {
public static int count(String filename) throws IOException {
InputStream is = new BufferedInputStream(new FileInputStream(filename));
try {
byte[] c = new byte[1024];
int count = 0;
int readChars = 0;
while ((readChars = is.read(c)) != -1) {
for (int i = 0; i < readChars; ++i) {
if (c[i] == '\n') {
++count;
}
}
}
return count;
} finally {
is.close();
}
}
public static String[] getContents(File aFile) throws IOException {
String[] words = new String[count(aFile.getName()) + 1];
BufferedReader input = new BufferedReader(new FileReader(aFile));
String line = null; //not declared within while loop
int i = 0;
while ((line = input.readLine()) != null) {
words[i] = line;
i++;
}
java.util.Arrays.sort(words);
for (int k = 0; k < words.length; k++) {
System.out.println(words[k]);
}
return words;
}
public static void main(String[] args) throws IOException {
File testFile = new File("try.txt");
getContents(testFile);
}
}
Here is the text file try.txt:
Daisy
Jane
Amanda
Barbara
Alexandra
Ezabile
the output is:
Alexandra
Amanda
Barbara
Ezabile
Jane
Daisy
To solve this problem I have to insert an empty line in the beginning of the text file, is there a way not to do that? I don't know what goes wrong?
I compiled your code (on a Mac) and it works for me. Try opening the file in a hexeditor and see if there is some special character at the beginning of your file. That might be causing the sorting to be incorrect for the first line.
You probably have a BOM (Byte Order Marker) at the beginning at the file. By definition they will be interpreted as zero-width non-breaking-space.
So if you have
String textA = new String(new byte[] { (byte)0xef, (byte)0xbb, (byte) 0xbf, 65}, "UTF-8");
String textB = new String(new byte[] { 66}, "UTF-8");
System.err.println(textA + " < " + textB + " = " + (textA.compareTo(textB) < 0));
The character should show up in your length of the strings, so try printing the length of each line.
System.out.println(words[k] + " " + words[k].length());
And use a list or some other structure so you don't have to read the file twice.
Try something simpler, like this:
public static String[] getContents(File aFile) throws IOException {
List<String> words = new ArrayList<String>();
BufferedReader input = new BufferedReader(new FileReader(aFile));
String line;
while ((line = input.readLine()) != null)
words.add(line);
Collections.sort(words);
return words.toArray(new String[words.size()]);
}
public static void main(String[] args) throws IOException {
File testFile = new File("try.txt");
String[] contents = getContents(testFile);
for (int k = 0; k < contents.length; k++) {
System.out.println(contents[k]);
}
}
Notice that you don't have to iterate over the file to determine how many lines it has, instead I'm adding the lines to an ArrayList, and at the end, converting it to an array.
Use List and the add() method to read your file contents.
Then use Collections.sort() to sort the List.

Categories

Resources