Get strings lenght from txt file and put string num and its lenght in log
902483Mar 9 2012 — edited Mar 23 2012Hello. I am a newbie in Java. Could you help to write a programm which looks into txt file, calculates the lenght of every string from the file and log the results?
For example, there is test.txt file located on d:\temp\test.txt
Is consists of:
122
61263
54545 45
1
I need to receive d:\temp\test_log.txt which include:
1 string lenght = 3
2 string lenght = 5
3 string lenght = 8
4 string lenght = 1
My problem is that i have not enough experience in Java and I just know the parts of this programm:
1. I can read file line by line:
import java.io.*;
class FileRead
{
public static void main(String args[])
{
try{
FileInputStream fstream = new FileInputStream("d:\\temp\\test.txt");
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine;
//Read File Line By Line
while ((strLine = br.readLine()) != null) {
// Print the content on the console
System.out.println (strLine);
}
//Close the input stream
in.close();
}catch (Exception e){//Catch exception if any
System.err.println("Error: " + e.getMessage());
}
}
}
2. Calculate string lenght:
public class StringLengthExample {
public static void main(String[] args) {
String string = "Count ";
int stringlength = string.length();
System.out.println("String lenght = "+stringlength);
}
}
3. and write the text to file:
public class RedirectSystemOut {
public static void main(String[] args) throws FileNotFoundException {
File file = new File("d:\\temp\\test_out.txt");
FileOutputStream fos = new FileOutputStream(file);
PrintStream ps = new PrintStream(fos);
System.setOut(ps);
System.out.println("Test record");
}
}
Could anybody help me to connect these parts into one programm which reads txt file string by string and creates a log with lenght for every string?
Or just give me an advise. Thank you.