Java combining two text files - java

I have an assignment for my Java class which asks me to combine two text files.
This is the code I have up until now.
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
public class CombineTwoFile {
public static void main(String[] args) throws IOException
{
ArrayList<String> list = new ArrayList<String>();
try
{
BufferedReader br = new BufferedReader(new FileReader( "A.txt"));
BufferedReader r = new BufferedReader(new FileReader( "B.txt"));
String s1 =null;
String s2 = null;
while ((s1 = br.readLine()) != null)
{
list.add(s1);
}
while((s2 = r.readLine()) != null)
{
list.add(s2);
}
}
catch (IOException e)
{
e.printStackTrace();
}
BufferedWriter writer=null;
writer = new BufferedWriter(new FileWriter("B.txt"));
String listWord;
for (int i = 0; i< list.size(); i++)
{
listWord = list.get(i);
writer.write(listWord);
writer.write("\n");
}
System.out.println("completed");
writer.close();
}
}
Now, when I compile it, i receive this message.
java.io.FileNotFoundException: A.txt (No such file or directory)
at java.io.FileInputStream.open(Native Method)
at java.io.FileInputStream.<init>(FileInputStream.java:120)
at java.io.FileInputStream.<init>(FileInputStream.java:79)
at java.io.FileReader.<init>(FileReader.java:41)
at CombineTwoFile.main(CombineTwoFile.java:15)
completed
I am using Coderunner on an Apple computer and i thought perhaps writing the text files as "C:/Users/dell/Desktop/Test/input1.txt" may fix the problem, however i am unsure on how to write that to correspond to my hard drive. Thanks for taking a look and i appreciate any help.

There are several things that could be improved here.
First, as others have pointed out, you need to specify the correct path to the file, the way you're doing it assumes that the files are in the classpath, and apparently they are not.
You can either specify the absolute path, or the relative path compared to the class.
If you want to leave it as is, you're gonna need to put the file in the classpath (where your class runs).
See this for additional info on absolute and relative path:
http://www.xyzws.com/javafaq/what-is-the-difference-between-absolute-relative-and-canonical-path-of-file-or-directory/60
Other than that, you shouldn't be throwing an Exception from main, instead, you should handle it.
I also suggest you use the new try-with-resources.
Example:
try(BufferedReader bf = new BufferedReader(new FileReader( "C:\\Users\\...\\A.txt"));){
//do something
} catch(IOException e){
//handle
}
//no need to close the streams, the jgc will handle that for you
This will close the streams for you when you're done using them, inside of the try block.
If your teacher (as you added in one comment) wants you to be able to dynamically select a path, you're gonna need to enter it from the console and use that as an absolute path.
Scanner s = new Scanner(System.in);
String path = s.readLine(); //use this as absolute path
If you need to do it from a GUI, you're gonna need a JFileChooser.
As far as writing goes, the same suggestions apply.
You could also avoid writing line + '\n' by using a PrintWriter.
It will provide a println(String s) method, auto-flush, and it's better for portability reasons.
As a minor note, in this case you do not actually need s2, using s1 again would do just fine.

Your Java program could not find 'A.txt' at desired location, to know where to put you file you can use system.getproperty( user.dir ) to know where system is looking for file. Other way is you can write absolute path in new File('c:\\something\\A.txt');
Hope it helps

Lucas, your program is absolutely right. you don't need to correct anything just create a file "A.txt" manually, then run this code again.

just place
System.out.println(new File("A.txt").getCanonicalPath());
before
BufferedReader br = new BufferedReader(new FileReader( "A.txt"));
BufferedReader r = new BufferedReader(new FileReader( "B.txt"));
you will get the exact path before the exception information like:
C:\Users\PiyushMittal\Downloads\Java-mongodb-hello-world-example\mongodb\A.txt
java.io.FileNotFoundException: A.txt (The system cannot find the file specified)
completed at java.io.FileInputStream.open0(Native Method)
at java.io.FileInputStream.open(FileInputStream.java:195)
at java.io.FileInputStream.<init>(FileInputStream.java:138)
at java.io.FileInputStream.<init>(FileInputStream.java:93)
at java.io.FileReader.<init>(FileReader.java:58)
at com.mkyong.core.CombineTwoFile.main(CombineTwoFile.java:19)
and very first line is the place where you have to put the file :)

Related

Reading text file works in IDE but not in .jar

I am using
File file = new File("res/movies.txt");
to read text from a bundled .txt file. My code works perfectly when running the program within IntelliJ IDEA, but when I create a .jar file and run it, it gives a "File not found" error. What can I do to make the code work both in the IDE as well as in the jar file?
You need to load the file as a resource. You can use Class.getResourceAsStream or ClassLoader.getResourceAsStream; each will give return an InputStream for the resource.
Once you've got an InputStream, wrap it in an InputStreamReader (specifying the appropriate encoding) to read text from it.
If you need to sometimes read from an arbitrary file and sometimes read from a resource, it's probably best to use separate paths to either create a FileInputStream for the file or one of the methods above for a resource, then do everything else the same way after that.
Here's an example which prints each line from resources/names.txt which should be bundled in the same jar file as the code:
package example;
import java.io.*;
import java.nio.charset.*;
public class Test {
public static void main(String[] args) throws IOException {
try (BufferedReader reader = new BufferedReader(
new InputStreamReader(
Test.class.getResourceAsStream("/resources/names.txt"),
StandardCharsets.UTF_8))) {
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
}
}
}
try to change
File file = new File("res/movies.txt");
to
File file = new File("res/movies.jar");
this of course assumes the filename is movies.jar

Accesing contents of a file in java

I wanted to know if there is any method in java to access the contents of the file in the computer.
For example if I want to make a word guessing game in which I want to access the words kept in a file randomly.
(I heard of something called "FileReader" but can't understand how to use it.)
Hope you understand what I mean.
Thanks!!
You can also read an entire text file as a List with Files.readAllLines . You can do it like this (read and print):
List<String> sl= Files.readAllLines(Paths.get("test1.txt"));
for (String s:sl) {
System.out.println(s);
}
Another option is to use Files.newBufferedReader like this:
try (BufferedReader br= Files.newBufferedReader(Paths.get("test1.txt")))
{
String line;
while ((line=br.readLine())!=null) System.out.println(line);
}
The try(){ } construct is called try-with-resorces, it closes the open file object (br in this case) automatically when finished. It is vital for writing, and is a good coding practice for reading.
You can read contents of File like this.
public void readFile(String fileName){ //Pass file's absolute path
BufferedReader reader = new BufferedReader(new FileReader(fileName));
String line = null;
while((line=reader.readLine())!=null){
System.out.println(line);
}
}

Always getting FileNotFoundException in java

I am using Scanner to read the File contents. For that I am using the following code.
public static void main (String[] args) throws IOException {
File file = new File("/File.txt");
Scanner sc = new Scanner(file);
while(sc.hasNextLine()) {
// Until the end
System.out.print(sc.nextLine());
}
sc.close();
}
But this code always throws FileNotFoundException. I have tried Googling this, but I can't find where to check the file. Secondly, I have created files with same name in almost every directory to check when would the Code catch the presence of file.
You can see in the Package I have created a file named File.txt so that code can find it whereever it looks for.
In the Java docs, I get to know that the File accepts a String parameter as
File file = new File("file_name");
But what sort or what would be the param here, isn't told. Can I get the help?
I think you want File file = new File("File.txt"); instead of File file = new File("/File.txt");, get rid of the slash. If what you want is a relative path, you want .\File.txt
As #deterministicFail says in the comments, it is not a good idea to hardcode path separators, instead use System.getProperty("path.separator"); This way your code should work in multiple plataforms, so your code would be:
To make it plataform independent (Asuming you are using a relative path):
File file = new File("." + System.getProperty("path.separator") + "File.txt");
Replace the line
File file = new File("/File.txt");
with
File file = new File(".\\File.txt");
or
File file = new File("File.txt");
File f=new File("testFile.txt");
For this kind of referral you need to put file in root of your eclipse project (In parallel of src). This problem is only when you are Using Eclipse IDE.
Best solution for this kind of problems is checking AbsolutePath of the file
System.out.println(f.getAbsolutePath());
It will give you path where your code is looking for file.
There are two possibilities if you are looking for the file in the working directory then either use "File.txt" or "./File.txt". In case of windows one more option would be to use ".\File.txt).
If that is not what you are looking for, you can check which path the file refers to using either of the two sysouts immediately after instantiating the file, which will give you the absolute path on your machine.
File f = new File("/File.txt");
System.out.println(f.getAbsolutePath());
System.out.println(f.getAbsoluteFile().getAbsolutePath());
I have never done it the way you did but this is how I read files.
This is the purpose of the class FileInpuStream. I use a buffer to get bytes.
If it is only a problem of path, why don't you simply use the complete path ? You can copy paste it from the file information.
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
public class Main {
public static void main(String[] args) {
FileInputStream fis = null;
try {
// object I use to read files
fis = new FileInputStream(new File("File.txt"));
byte[] buf = new byte[8];
int n = 0;
// while there is something in the file
while ((n = fis.read(buf)) >= 0) {
for (byte bit : buf) {
// do what you want
System.out.print("\t" + bit + "(" + (char) bit + ")");
System.out.println("");
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
if (fis != null)
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
Try not to use the / in File.txt, and if you really have to, use the backslash instead \ since you're in Windows

Creating a File using PrintWriter in Java, and Writing to that File

I'm trying to write a program that reads a file (which is a Java source file), makes an Arraylist of certain specified values from that file. and outputs that Arraylist into another resulting file.
I'm using PrintWriter to make the new resulting file. This is a summarised version of my program:
ArrayList<String> exampleArrayList = new ArrayList<String>();
File actualInputFile = new File("C:/Desktop/example.java");
PrintWriter resultingSpreadsheet= new PrintWriter("C:/Desktop/SpreadsheetValues.txt", "UTF-8");
FileReader fr = new FileReader(actualInputFile);
BufferedReader br = new BufferedReader(fr);
String line=null;
while ((line = br.readLine()) != null) {
// code that makes ArrayList
}
for (int i = 0; i < exampleArrayList.size(); i++) {
resultingSpreadsheet.println(exampleArrayList.get(i));
}
resultingSpreadsheet.close();
The problem is that when i run this, nothing gets printed to the resultingSpreadsheet. It's completely empty.
BUT, this program works perfectly (meaning that it prints out everything correctly to the resultingSpreadsheet file) when I replace:
File actualInputFile = new File("C:/Desktop/example.java");
which is the file that I want as my input file, and which has a size of 481 KB,
with:
File smallerInputFile = new File("C:/Desktop/smallerExample.txt");
which is really just a smaller .txt example version of the .java source file, and it has a size of 1.08 KB.
I've tried a few things including flushing the PrintWriter, wrapping it around FileWriter, copy-pasting all the code from the .java file into a text file in case it was an extension problem, but these don't seem to work.
I'm starting to think it must be because of the size of the file that the PrintWriter makes, but it's very possible that that's not the problem. Perhaps I need to put everything in a stream (like it says here: http://docs.oracle.com/javase/6/docs/api/java/io/PrintWriter.html)? If so, how would I do that?
Why is reading the bigger actualInputFile and outputting its data correctly such a problem, when everything works fine for the smallerInputFile?
Can anyone help with this?
Check for exceptions while writing to the the excel sheet , because i really don't think its a problem of size. Below is the sample code that is executing successfully and the file size was approx 1 MB.
public class Test {
/**
* #param args
*/
public static void main(String[] args) {
BufferedReader br = null;
try {
String sCurrentLine;
br = new BufferedReader(new FileReader("D:\\AdminController.java"));
while ((sCurrentLine = br.readLine()) != null) {
System.out.println(sCurrentLine);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (br != null)br.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
}
This should go as a comment, but I do not have the rep. In the documentation it has both write methods and print methods. Have you tried using write() instead?
I doubt it's the size of the file, it may be between the two files you are testing one is .txt, and the other is .java
EDIT: Probably second suggestion of the two. First is just something I noticed with the docs.
The methods of PrintWriter do not throw Exception. Call the checkError() method which would flush the stream as well as return true if an error occurred. It is quite possible that an error occurred processing the larger file, an encoding error for instance.
Check your program. When the file is empty it means that your program doesn't close the PrintWriter before finishing the program.
For example you may have a return in a part of your program which cause that resultingSpreadsheet.close(); have not being run.

What's the difference between File and FileLoader in Java?

So I have the following code where I should read a Text File (This is just the Main Class):
import gui.MenuWindow;
import java.io.IOException;
import javax.swing.JOptionPane;
public class Assessor {
public static void main(String args[]) throws IOException {
FileLoader file = new FileLoader("Example.txt");
try{
new MenuWindow(file.loader());
} catch(Exception exc) {
JOptionPane.showMessageDialog(null, "Error Reading File");
}
}
}
Then I'd have to load the Text into a ListBox using Swing. The thing is that I've found this new code to read a Text File:
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileNotFoundException;
import java.io.IOException;
public class ReadTextFileExample {
public static void main(String[] args) {
File file = new File("test.txt");
StringBuffer contents = new StringBuffer();
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader(file));
String text = null;
// repeat until all lines is read
while ((text = reader.readLine()) != null) {
contents.append(text)
.append(System.getProperty(
"line.separator"));
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (reader != null) {
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
// show file contents here
System.out.println(contents.toString());
}
}
So I'd like to know what is the difference between the following two lines:
FileLoader file = new FileLoader("Example.txt"); //First Code
File file = new File("test.txt"); //Second Code
And... What's the StringBuffer and BufferedReader used to? Thanks!
So I'd like to know what is the difference between the following two lines:
FileLoader file = new FileLoader("Example.txt"); //First Code
File file = new File("test.txt"); //Second Code
The first creates a java.io.FileLoader which Andreas discusses. Since the javadoc says "The constructors of this class assume that the default character encoding and the default byte-buffer size are appropriate", it should never be used.
The second creates a java.io.File which is just a file path with some utility methods that can be used to read directory trees, delete, create, and move files, etc., or it can be used with FileInputStream and other classes to actually access the file contents.
And... What's the StringBuffer and BufferedReader used to? Thanks!
The StringBuffer is used to collect the contents of the file.
The BufferedReader is used to speed up reading of the file. Instead of reading one character at a time, the BufferedReader batches reads using an internal buffer.
This is an exemplary question about learning Java SE, especially regarding the java.io package. I was a bit puzzled in the beginning, but now I am quite sure that you want to compare the FileReader to the File class, which both belong to the same package java.io.
File in the Java SE API:"An abstract representation of file and directory pathnames."In other words, it is there to handle files and directories on the file system within Java. Since Java is an object-oriented language, they made a class for it. Files, i.e. binary and text files, share some attributes in common with directories, as there are: absolute, canonical path and simple name, etc.Of course, File is one of the base classes in the java.io package and many classes like FileReader make use of it for object construction.
FileReader:"Convenience class for reading character files."It comes with a handy constructor that takes a file name or file path as a String. Originally, it was meant to be constructed by a File instance. A Reader instance in general is practical to read text files, in contrast to InputStream, which is used to read binary files. A Reader instance in general is connected to a character set, e.g. "UTF-8" to translate byte to character streams.
Please also have a look at the excellent Java Tutorials provided by Oracle.
I hope the difference between File and FileReader becomes a little clearer. Especially note that there is no I/O, when you instantiate a File instance. To answer your question, the interconnection of the two classes would be:
File file = new File("test.txt"); // 1) Instaniate the file
Reader reader = new FileReader(file); // 2) Instantiate the Reader using the File instance
When you wrap a BufferedReader around a Reader instance, you can read the text file linewise, as:
BufferedReader bufferedReader = new BufferedReader(reader); // 3) Get a "buffered reader" to have access line by line.
StringBuffer comes in, when you want to chain a large number of String objects, since String objects is immutable and string operations like
String s1 = "Star ";
String s2 = "Wars";
s1 = s1 + s2;
are very costly, especially in loops, since at every addition a new String object (left side result) is created, with practically no size limits, apart from the reserved Java VM heap space.
Let me point out that you should better use the StringBuilder class, which is even faster, and is the unsynchronized counter-part of StringBuffer, introduced in the Java 5 release. The feature that StringBuffer is guaranteed to be synchronized among different Thread's is hardly ever used. I never came across it in my whole life as Java programmer.

Categories

Resources