how to add two words from text file using java program - java

I am new to java. I think this is the simplest problem but even i dont know how to solve this problem. I have one text file. In that file i have some words like below :
good
bad
efficiency
I want to add list of words into another by using java program. My output want to be like this
good bad
good efficiency
bad efficiency
How to get this using java program. I tried search for some ideas. But i wont get any idea. Please suggest me any ideas. Thanks in advance.

If you do not want to learn it from scratch I would recommend using the Apache Commons io library.
The FileUtils class has a simple interface to read from and write to a file.

A good place to start learning Java IO would be to look over Sun's Java Tutorials on File IO. If you're looking into how to read in individual lines, I would particularly look at Scanners. And if at some point you're looking to manipulate Strings like this without IO being heavily involved, I'd look at Java's StringBuilder.

import java.io.*;
class Test {
//--------------------------------------------------< main >--------//
public static void main (String[] args) {
Test t = new Test();
t.readMyFile();
}
//--------------------------------------------< readMyFile >--------//
void readMyFile() {
String record = null;
String rec=null;
int recCount = 0;
try {
FileReader fr = new FileReader("c:/abc/java/prash.txt");
FileReader fr1 = new FileReader("c:/abc/java/pras.txt");
BufferedReader br = new BufferedReader(fr);
BufferedReader br1 = new BufferedReader(fr1);
record = new String();
rec = new String();
while ((record = br.readLine()) != null && (rec=br1.readLine())!=null) {
// recCount++;
System.out.print(record +" "+ rec);
//System.out.print(rec);
}
} catch (IOException e) {
// catch possible io errors from readLine()
System.out.println("Uh oh, got an IOException error!");
e.printStackTrace();
}
} // end of readMyFile()
} // end of class

Related

Creating commands for a terminal app in Java

I'm new to programming, and I'm making an app that only runs in the command-line. I found that I could use a BufferedReader to read the inputs from the command-line.
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
String Input = "";
while (Input.equalsIgnoreCase("Stop") == false) {
Input = in.readLine();
//Here comes the tricky part
}
in.close();
What I'm trying to do now is to find a way to create different "commands" that you could use just by typing them in the command-line. But these commands might have to be used multiple times. Do I have to use some kind of Command design pattern with a huge switch statement (that doesn't seem right to me)? I'd like to avoid using an extra library.
Can someone with a bit more experience that me try to help me?
You could try something like this:
public static void main(String[] args) {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
String input = "";
try {
while (!input.equalsIgnoreCase("stop")) {
showMenu();
input = in.readLine();
if(input.equals("1")) {
//do something
}
else if(input.equals("2")) {
//do something else
}
else if(input.equals("3")) {
// do something else
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
public static void showMenu() {
System.out.println("Enter 1, 2, 3, or \"stop\" to exit");
}
It is good practice to keep your variables lower cased.
I would also say that !Input.equalsIgnoreCase("stop") is much more readable than Input.equalsIgnoreCase("stop") == false although both are logically equivalent.
If it's just about reading the program parameters you can just add them behind the Java application call and access them through your args argument of your main method. And then you can loop through the array and search for the flags your program accepts.

Beginner Java Task file writer

I am trying to make a java program that appends text into an existing document. This is what it has gotten me at:
import java.util.*;
import java.io.*;
public class Main
{
public main(String args[])
{
System.out.print("Please enter a task: ");
Scanner taskInput = new Scanner(System.in);
String task = taskInput.next();
System.out.print(task);
PrintWriter writer = new PrintWriter("res\tasks.txt", "UTF-8");
writer.println("The first line");
writer.println("The second line");
writer.close();
}
}
I have some errors and do not know how to fix them. I looked at the Bufferedwriter but I don't know how it's used, and yes I have looked javadocs. C++ was not nearly this complicated. Once again, I want to know how to make the program append text to an existing file. It should be efficient enough to make into an app. Are there any good resources to teach how to write/append/read files?? javadoc is not doing it for me.
The main() method in Java has to have the following signature
public static void main(String[] args)
Without the method being declared as above, JVM would fail to run your program. And, just like you closed the PrintWriter, you need to close your Scanner too.
I suggest you get the basics of Java down before diving into File I/O because this API would throw a lot of checked Exceptions too and for someone this new to Java it would just be terribly confusing as to what the try catchs or throws are doing.
try this,
PrintWriter writer = new PrintWriter(new BufferedWriter(new FileWriter("tasks.txt", true)));
The following should work:
public static void main(String[] args) {
try{
Formatter out = new Formatter("fileName.txt");
out.format("Write this to file");
out.close();
} catch (Exception e) {
System.out.println("An error occurred");
}
}
This is using a Formatter object to create a file (if it doesn't already exist) and then you can use the method "format" just like you would use any print method to write to the file. The try and catch is necessary for it to compile b/c the constructor of the Formatter class throws an exception that must be caught. Other than that, just make sure you type:
import java.util.Formatter;in the beginning of your file.
And btw, C++ is NOT easier than Java lol. Cheers.

alternative to readLine() method in BufferedReader?

I am new to java Network programming.I was googling the code for a TCP client in java.I came across the following example.
import java.lang.*;
import java.io.*;
import java.net.*;
class Client {
public static void main(String args[]) {
try {
Socket skt = new Socket("localhost", 1234);
BufferedReader in = new BufferedReader(new
InputStreamReader(skt.getInputStream()));
System.out.print("Received string: '");
while (!in.ready()) {}
System.out.println(in.readLine()); // Read one line and output it
System.out.print("'\n");
in.close();
}
catch(Exception e) {
System.out.print("Whoops! It didn't work!\n");
}
}
}
The client seems to read out the data one "line" at a time?. I am connecting to a server that is streaming OpenFlow packets.A wireshark screenshot of OpenFlow packets is given below.
[http://www.openflow.org/downloads/screenshot-openflow-dissector-2008-07-15-2103.jpg][1]
Once I recieve the complete packets I want to dump that to a file and then later read it using wireshark for example.In the above code they are using calss BufferedReader to read the data in "lines"? At least that is how I understand it.Is there someway in which I can get full packets and then write it to the file?
Readers are for working with text data. If you are working with binary data (it's not entirely clear from that screenshot), you should be working with some type of Stream (either InputStream or possibly DataInputStream). Don't just look for random examples on online, try to find ones that actually apply to what you are interested in doing.
also, don't ever use InputStream.available, it's pretty much useless. as is any example code using it.
also, a simple google search for "OpenFlow java" had some interesting hits. are you sure you need to write something from scratch?
No, but there are libraries that provides such functions. See for example Guava
http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/io/ByteStreams.html
If you don't want to (or can't) use libraries you shoud consume a stream like this
List<String> lst = new ArrayList<String>();
String line;
while ((line = in.readLine()) != null) {
lst.add(line);
}
or
String str = "";
String line;
while ((line = in.readLine()) != null) {
str += line + "\n";
}
Note that the BufferedReader.readLine() method will give you a new line on linebreaks ('\n'). If the InputStream is binary you should work with bytes instead.

Improve performance of a Java Program

I've made an Applet Search Utility in which I provide a string as input and find that string in the specified file or folder.
I've done with this but I m not happy with its performance.
The process is taking too much time to respond.
I decided to do its profiling to see what is happening and I noticed that the method scanner.hasNextLine() is taking most of the time.
Though this is very important method for my program because I have to read all the lines and find that string, Is there any other way by which I can improve its performance and reduce the execution time
Here is the code where I am using this method ....
fw = new FileWriter("filePath", true);
bw = new BufferedWriter(fw);
for (File file : filenames) {
if(file.isHidden())
continue;
if (!file.isDirectory()) {
Scanner scanner = new Scanner(file);
int cnt = 0;
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
if(!exactMatch)
{
if(!caseSensitive)
{
if (line.toLowerCase().contains(searchString.toLowerCase())) {
// System.out.println(line);
cnt += StringUtils.countMatches(line.toLowerCase(),
searchString.toLowerCase());
}
}
else
{
if (line.contains(searchString)) {
// System.out.println(line);
cnt += StringUtils.countMatches(line,
searchString);
}
}
}
And yes the method toLowerCase() is also taking more time then expected.
I have changed my code and now I am using BufferedReader in place of Scanner as Alex and Nrj suggested and I found a nice improvement in the performance of my application.
It is now processing in one third time of its earlier version.
Thanks to all that replied.....
Following your question I examined code of Scanner and I think that your are right. It is not optimized to work with large data. I'd recommend you to use simple BufferedReader that wraps InputStreamReader that wraps FileInputStream:
BufferedReader r = new BufferedReader(new InputStreamReader(new FileInputStream(fileName)))
then read line-by-line:
r.readLine()
If this is not enough for you try to read bulks of lines and then process them.
Concerning to toLowerCase() you can try to use regular expressions instead. The benefit is that you do not have to change the case of line every time. The disadvantage is that in simple cases regular expression works a bit slower than regular string comparison.
I would suggest redesigning your solution and use something like Lucene to do the search for you. You can index and search files with Lucene much more efficiently, tutorial on how to do it with text files can be found here: http://www.avajava.com/tutorials/lessons/how-do-i-use-lucene-to-index-and-search-text-files.html
(Only small optimizations, in response to comment above.)
if(!caseSensitive)
{
searchString = searchString.toLowerCase();
}
while (true) {
String line = bufferedReader.readLine();
if (line == null)
break;
if(!caseSensitive)
{
line = line.toLowerCase();
}
if(!exactMatch)
{
if (line.contains(searchString)) {
// System.out.println(line);
cnt += StringUtils.countMatches(line,
searchString);
}
}
Try using BufferedReader
Make use of threads. You can search the files in parallel which should reduce the search time.
I would not use Java to search the file system for matches of the string. Instead invoke a native algorithm from Java instead. I would invoke grep from Java using something like this:
ProcessBuilder pb = new ProcessBuilder("grep", "-r", "foo");
pb.directory(new File("myDir"));
Process p = pb.start();
InputStream in = p.getInputStream();
//Do whatever you prefer with the stream

java equivelant to uix cut

i'm not a java coder but need a commnad that will do
cut -d "/" -f1,2,3 MyFile
Any ideas?
Read the file. Split each line on / and then print out the first three parts.
BufferedReader in = null;
try{
in = new BufferedReader(new FileReader("MyFile"));
String line = "" ;
while((line = in.readLine()) != null){
String[] fields = line.split("/");
System.out.printf("%s/%s/%s\n", fields[0], fields[1], fields[2]) ;
}
}
catch(Exception e){
e.printStackTrace();
}
finally{
if (in != null) {
try {
in.close();
} catch (IOException e) {
}
}
}
The main difference between Java coding and that script example is that they use different programming paradigm lest say that Java use Object Programing and that example can be assigned to declarative programing (You only express the logic, not the way to get the result) so no commands in Java.
So there is no command that You can use for this type of functionality.
There might be some package with this type of static procedure that works like that cut program. But still You will have to write a program to use it.
So if You would describe us the purpose of usage of this program (cut) )we could be able to provide You a good answer.

Categories