I/O Java

I/O Java

import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.PrintWriter; import java.util.Scanner; public class Concat {

public boolean accept(File file) {
    //if the file extension is .txt or .java return true, else false
    if (file.getName().endsWith(".txt")||file.getName().endsWith(".java")) {
        return true;
    }
    return false;
}

public void copy(PrintWriter pw, String inputFile)
{
    File f = new File(inputFile);
    if(accept(f)==true){

        try {
            Scanner scan = new Scanner(f);
            pw= new PrintWriter(new FileOutputStream("Stuff.txt"));
            while (scan.hasNextLine())
            {
                String s = scan.nextLine();
                pw.println(s);
            }
            scan.close();
        } catch (FileNotFoundException e) {
            System.out.println(" Error: "+e + " "+ inputFile);
        }
    }else{

        System.out.println("File name must be a TEXT Or JAVA type");

    }
}

// The routine will throw a RuntimeException if the inputFile name does 
// note end with .java or .txt

// This routine will also throw a RuntimeException if any problem occurs in 
// opening the inputFile

// The copy routine copies the contents of the inputFile into the PrintWriter


public void concat(String outFile, String[] inputFiles)
{
    try {
        PrintWriter writer = new PrintWriter(outFile);
        for(int i=0;i<inputFiles.length;i++){
            String source=inputFiles[i];
            copy(writer,source);
        }

    } catch (IOException e) 
    {
        System.err.println(e);
        System.exit(1);
    }

    // Fill in details.
    // The routine will call copy to do a copy of a single file
    // This routine will also create an open PrintWriter for the outFile
    // If any problem occurs, a RuntimeException should be thrown with 
    // appropriate error information
}


public static void main(String[] args) {
    if (args == null || args.length < 2)
    {
        System.out.println("Concat needs at least 2 filenames");
        return;
    }
    try
    {

        String[] inputFiles = new String[args.length-1];
        for (int i=0; i < inputFiles.length; i++)
            inputFiles[i] = args[i+1];
        Concat c = new Concat();
        c.concat(args[0], inputFiles);
    }
    catch (RuntimeException e)
    {
        // Possible errors:
        // An input file that doesn't end with .java or .txt
        // An input file that doesn't open properly.
        // Trouble creating the output file

        System.out.println(" Error in Concat:"+e);
    }
}

}

View Answers

September 12, 2012 at 1:45 AM

I am not really sure why This program is not running properly? Any ideas? Thanks in advance.


September 13, 2012 at 1:02 PM

Here is an example of concatenating text files.

import java.io.*;
import java.util.*;

public class Concat {

        static public void main(String arg[]) throws java.io.IOException {
                PrintWriter pw = new PrintWriter(new FileOutputStream("c:/concat.txt"));
                Scanner input=new Scanner(System.in);
                System.out.print("How many files you want to concat?:");
                int no=input.nextInt();
                String f[]=new String[no];
                System.out.println("Enter filenames: ");
                for(int i=0;i<f.length;i++){
                    String filename=input.next();
                    int mid= filename.lastIndexOf(".");
                    String ext=filename.substring(mid+1,filename.length());
                    if(ext.equals("txt")){
                    f[i]=filename;
                      System.out.println("Processing " + f[i] + "... ");
                        BufferedReader br = new BufferedReader(new FileReader(f[i]));
                        String line = br.readLine();
                        while (line != null) {
                                pw.println(line);
                                line = br.readLine();
                        }
                        br.close();
                    }
                    else{
                        System.out.print("Only txt files should be concated.Re-enter file name: ");
                    }
                }
                 pw.close();
                System.out.println("All files have been concatenated into concat.txt");
        }
}

Ads









Related Tutorials/Questions & Answers:
java i/o operations
java i/o operations  how to write integer data to a file in java using random access file object or file writer or data outputstream i have already tried the write and writeInt methods....plz help
Java i/o opearations
Java i/o opearations  "FOLLOWING IS MY LAST QUESTION ON JAVA I/O... to a file in java using random access file object or file writer or data outputstream i..."),true)); for(int i=1;i<=10;i++){ System.out.print("Enter Number
Advertisements
Java I/O problem
Java I/O problem   Write a Java application that prompts the user to input their Name, Address, Date of Birth and Student ID number using the standard input - this information should then be saved to a file named studentData
I/O Java
I/O Java  import java.io.File; import java.io.FileNotFoundException...(File file) { //if the file extension is .txt or .java return true, else false if (file.getName().endsWith(".txt")||file.getName().endsWith(".java
Java I/O
Java I/O  how to write different type of arrays like string,int,double etc into a file using DataOutputStream
Java I/O Data Streams
Java I/O Data Streams In this tutorial we will discuss the Java I/O Data Streams. To deal with the binary I/O of primitive data type values as well as the String values Java provided the support of Data stream. DataInput
Java I/O From the Command Line
Java I/O From the Command Line In this section we will learn about the I/O from the command line in Java. Several times you can see that the programs runs after taking the input from the command line. Java also supports for the command
I/O stream class.
I/O stream class.  Explain the hierarchy of Java I/O stream class.   Hierarchy of Java I/O streams Have a look at the following link: Java I/O
Java I/O Character Streams
Java I/O Character Streams In this section we will discuss the I/O Character... and for this Java provides the Character stream I/O. Character stream I/O... the character stream I/O the character stream classes are defined. These classes
Java I/O Byte Streams
Java I/O Byte Streams In this section we will discussed the I/O Byte Streams... are used where the program needs to work with the raw binary data. In Java to handle I/O raw binary data the byte stream classes are defined. For all of the byte
Java I/O Buffered Streams
Java I/O Buffered Streams In this section we will discuss the I/O Buffered Streams. In Java programming when we are doing an input and output operation then we are trying to interact our Java program to read from or write data
i/o
i/o  java program using inputstream and outputstream   Hi Friend, Try the following code: import java.io.*; class InputStreamAndOutputStream { public static void main(String[] args)throws
i/o
i/o  java program using inputstream and outputstream   Hi Friend, Try the following code: import java.io.*; class InputStreamAndOutputStream { public static void main(String[] args)throws Exception
i/o
i/o  java program using inputstream and outputstream   Hi Friend, Try the following code: import java.io.*; class InputStreamAndOutputStream { public static void main(String[] args)throws Exception
i/o
i/o  java program using inputstream and outputstream   Hi Friend, Try the following code: import java.io.*; class InputStreamAndOutputStream { public static void main(String[] args)throws Exception
i/o streamas
i/o streamas  java program using bufferedreader and bufferedwriter   Hi Friend, Try the following code: import java.io.*; class BufferedReaderAndBufferedWriter{ public static void main(String[] args) throws
I/O to another applications
I/O to another applications  **What if there exists an application that needs a certain input and will give an output. Using Java, how can we invoke...); System.out.print("Enter integer: "); int i=input.nextInt
find a substring by using I/O package
find a substring by using I/O package  Write a java program to find a sub string from given string by using I/O package
file I/O
file I/O  Write a java class which it should do below Read the attached file. Sorted out and writer it into another file(sorted values). Also find the SECOND biggest number in the attached file
Java I/O Object Streams
Java I/O Object Streams In this section we will discuss the Java IO Object Streams. To work with the I/O of objects Java provided the support of Object... data types and graphs of Java objects into an output stream. This class can
I/O Program output error
I/O Program output error  Hello All, I am working on a program... file, but I am getting incorrect output. I have been successfull with part of the program in that it reads the text file and analyzes it, however I need it to take
What is Java I/O?
What is Java I/O?       Introduction The Java Input/Output (I/O) is a part of java.io package.... How Files and Streams Work: Java uses streams to handle I/O operations
Write a program that replaces a, e, i, o, u in Java2
Write a program that replaces a, e, i, o, u in Java2  Write a program that replaces a, e, i, o, u, with the letter z. (i.e. John Smith -> Jzhn Smzth. Also the program reverses the users name (i.e. John Smith -> htimS nhoJ
Creating a File I/O using import scanner, io.* and text.*
Creating a File I/O using import scanner, io.* and text.*  open a file for reading and open another file for writing data. input file hours-int, hourly rate-double, name-string. output file name-string, hours-int, hourly rate
Scanning and Formatting in Java
Scanning and Formatting in Java In this we will discuss about the Java I/O Scanning and Formatting. In the perspective of programming in Java I/O we... a programmer does programming of I/O the input data undergoes with the translation
File I/O
File I/O  greetings i was running into a problem. is their a way...(); File[] files = file.listFiles(filter); for (int i = 0; i < files.length; i++) { System.out.println("Processing " + files[i].getPath
File I/O
File I/O  i am trying to write a program that reads a text file... the text file then read it and write it into as a comma delimitade file. i have... file it has two fields, the left and write field i write out only the right
File I/O
File I/O  i have a problem i am trying to print on a new line every time i reach a certain condition "if(line.startsWith("Creating"))" i want... = file.listFiles();//listFiles all file in inpath dir for (int i = 0; i <
File I/O
File I/O  i am trying to read and write a file. my program works perfectly i am using PrintWriter and BufferedReader. but my problem is that when reading line by line if i reach a certain conditions like "if(line.startsWith
File I/O
File I/O  i am trying to read and write a 54mb text file from one directory to another. I managed to do it perfectly using the examples i was given... question is, is their away i can read and write in the shortes time possible(in seconds
Changes in I/O
Changes in I/O       This is a new feature added in Java SE 6, which has the ability to read... is provided by java.io.Console Class which is newly added in JAVA SE 6. Reading
Factorial Program in Java
execution of the program. BufferReader is defined under the Java I/O package...Factorial program in Java helps programmer to write factors of any given.... InputStreamReader reads the input from user and then keep it into a buffer. As Java reads
Introduction to Filter I/O Streams
Introduction to Filter I/O Streams....  Like I/O streams, Filter streams are also used to manipulate... from I/O streams can be shown as: There are two streams, that are derived from
Overview of I/O Data Streams
Overview of I/O Data Streams   ... of the Filter I/O streams derived from I/O streams can be shown as: In this section we will learn about the Data I/O streams derived from the Filter I/O
Use of Image I/O library
Use of Image I/O library       This section illustrates you how to use Image I/O library. The ImageIO class provides the method to read and write image. We are providing you
Read Text from Standard IO
); Working with Reader classes: Java provides the standard I/O... from the keyboard and write output to the display. They also support I/O...; IOException, if an I/O error occurs.  Method
URLInformation
. This exception is thrown to indicate an I/O problem. The IO exception is defined in java.io... of this program: C:\rose>javac URLInformation.java C:\rose>java
EchoClientSocket
for the exception handling. This exception is thrown to indicate an I/O problem... C:\amar>java EchoClientSocket Socket[addr=roseindi/192.168.10.104,port=135,localport=1368] I understand about the host: roseindi
File handling in Java, Java Files
handling in Java. The Java programming language provides I/O System for handling the files. The I/O system is packaged under java.io package. This package... be used for I/O operations. There one more package; java.util.zip, that can
Java ioexception
of  I/O problem has occurred. This is the general class of exceptions generated when any I/O operation gets failed or interrupted. Its sub classes... Java ioexception      
Java NIO Package Tutorial
. Java NIO package provides advanced and efficient I/O functionality... I/O API works with byte streams and character stream but NIO I/O API works with channel and buffers making it faster while performing I/O
What is Java Client Socket?
an IOException for the exception handling. This exception is thrown to indicate an I/O...What is Java Client Socket?  Hi, What is client socket in Java... socket connections. To get connection in client socket in java used the class
File Handling In Java
for example a console, file, buffer, etc.  In Java you will see the various I... and formatted text. I/O from the Command Line : This Stream handles the Standard Streams...File Handling In Java In this section we will discussed about How files can
Networking in Java
at how it relates to all of these networking concepts. In Java we can build I/O objects across the network by extending the I/O interface. Java supports most... for reliable stream-based I/O across the network and UDP supports the point-to-point
Networking in Java
at how it relates to all of these networking concepts. In Java we can build I/O objects across the network by extending the I/O interface. Java supports most... for reliable stream-based I/O across the network and UDP supports the point-to-point
Classes in Java
of the exceptions. Basic I/O: In this section we will learn about basic input..., primitive data types, objects etc. We will learn about I/O Steams and how to use... Classes in Java      
Example to compile a java file with the help of the program
generally invokes  the tool to run with the given I/O channels and arguments... Example to compile a java file with the help of the program... are describing you the way to compile the java file with the help of the java program
JAVA Objectives Question?
have used FileInputStream and FileOutputStream for I/O operations. import...JAVA Objectives Question?  Write an application using...(); for (int i=0; i < buf.length; i += 2) { fos.write(buf[i
IO Streams in Java with Examples
in it. Java I/O streams are divided into: Input streams - for reading data...: Here are examples of  IO Streams in Java, the i/o classes are packaged.... These input and output streams can be file input stream or stream input streams. Java I
Core Java Interview Question, Interview Question
do threads block on I/O? Answer: Threads block on i/o (that is enters the waiting state) so that other threads may execute while the i/o Operation is performed... Core Java Interview Question Page 12  

Ads