Combining text file using method - java

Hi everyone I am currently trying to write a program for an assignment that takes 4 separate text files then using a method, combines them into one. I was wondering if someone could help me find out what is wrong with this code. When i try to run it I get a error reading the following:
"Exception in thread "main" java.io.FileNotFoundException: wonder1.txt (The system cannot find the file specified)
at java.io.FileInputStream.open(Native Method)
at java.io.FileInputStream.<init>(Unknown Source)
at java.util.Scanner.<init>(Unknown Source)
at asig5.combineFile(asig5.java:26)
at asig5.main(asig5.java:17) "
Code:
import java.io.IOException;
import java.io.PrintWriter;
import java.io.File;
public class asig5 {
public static void main(String[] args) throws FileNotFoundException {
PrintWriter newtext = new PrintWriter("wonder5.txt");
File f0 = new File("wonder1.txt");
File f1 = new File("wonder2.txt");
File f2 = new File("wonder3.txt");
File f3 = new File("wonder4.txt");
combineFile(f0, newtext);
combineFile(f1, newtext);
combineFile(f2, newtext);
combineFile(f3, newtext);
newtext.close();
}
public static void combineFile(File f0, PrintWriter output) throws FileNotFoundException {
Scanner input = new Scanner(f0);
while (input.hasNext()) {
String part1 = input.nextLine();
System.out.println(part1);
output.print(part1);
}
}
}

When you write new File("wonder1.txt") it means that if your project location is ~/Folder/MyProject, your file's full path is ~/Folder/MyProject/wonder1.txt.
You need to provide full path to your file or put your files at the root of your project folder.

Related

Passing a file as a paramater to another class in Java throws the error "File or Directory not found"

I'm trying to pass a file from the main method to another class that should handle it, but while the file is recognized in the main class, it throws this error in the second one.
Exception in thread "main" java.io.FileNotFoundException: file:/home/giovanni/Desktop/spring-course/exercises-part2/word-inspection/target/classes/words.txt (File o directory non esistente)
at java.base/java.io.FileInputStream.open0(Native Method)
at java.base/java.io.FileInputStream.open(FileInputStream.java:219)
at java.base/java.io.FileInputStream.<init>(FileInputStream.java:157)
at java.base/java.util.Scanner.<init>(Scanner.java:639)
at com.vanny96.WordInspection.<init>(WordInspection.java:16)
at com.vanny96.App.main(App.java:13)
The path for the file is correct, and the file is there, so I have no idea why it isn't working.
I tried looking around for a solution but couldn't find any, and the fact that the file works fine in the main method while not in another one confused me a lot, if you could point me to a thread where this is solved it would be enough!
Here is the code:
Main App
package com.vanny96;
import java.io.File;
import java.io.FileNotFoundException;
import java.net.URL;
public class App {
public static void main(String[] args) throws FileNotFoundException
{
URL fileUrl = App.class.getClassLoader().getResource("words.txt");
File file = new File(fileUrl.toString());
WordInspection inspector = new WordInspection(file);
}
}
WordInspection class
package com.vanny96;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class WordInspection {
private File file;
private Scanner reader;
public WordInspection(File file) throws FileNotFoundException {
this.file = file;
this.reader = new Scanner(this.file);
}
}
I think the Scanner is not able to resolve the file as an URL, but is able to resolve it as an URI.
If you change the line:
File file = new File(fileUrl.toString());
to
File file = new File(fileUrl.toURI());
your Scanner should be able to resolve the file (i have tested it). You will have to add an additional throws class for the toUri() method.

NullPointerException in BufferedReader

I'm trying to use BufferedReader to import strings from a .txt file into an Arraylist, then using a random method to randomly pick a string inside the Arraylist.
But whenever I run this code, it gives me a java.lang.NullPointerException.
What should I do to fix this problem? Thank you in advance.
java.lang.NullPointerException
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at edu.rice.cs.drjava.model.compiler.JavacCompiler.runCommand(JavacCompiler.java:272)
the .txt file in question consists of a few lines of words.
import java.util.ArrayList;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.Random;
public class WordList{
private static ArrayList<String> words =new ArrayList<String>();
public void main(String[] args) throws IOException {
ArrayListCon("Majors.txt");
System.out.println(words);
}
private void ArrayListCon(String filename) throws IOException{
String line;
BufferedReader br = null;
br = new BufferedReader(new FileReader(filename));
while (( line = br.readLine()) != null){
words.add(line);
}
br.close();
}
public static String getRandomWord(){
Random r = new Random();
String randomWord = words.get(r.nextInt(words.size()));
return randomWord;
}
}
After making the following changes, your code worked perfectly for me, and i never saw the null pointer exception error.
1 ) I first made the method main static, as I was getting an error that there was no main method found:
public static void main(String[] args) throws IOException {
2 ) I also made the ArrayListCon method static
private static void ArrayListCon(String filename) throws IOException{
3 ) I made a file called Majors.txt with the contents:
hello
hi
there
my
words
are
cool
4 ) Finally, I just compiled and ran the program, with the following output:
javac WordList.java
java WordList
[hello, hi, there, my, words, are, cool]
I believe the issue is coming up with how you are running the code (edu.rice.cs.drjava.model.compiler.JavacCompiler)
The exception is arising as a result of a bug in both your code and in the DrJava code.
In your code, you need to make your main method static.
In the DrJava code, they need to add a check for Modifier.isStatic(m.getModifiers()) in the JavacCompiler.runCommand method.

File Not Found Exception - Can't see the issue

I've tried directly linking using the entire path but that hasn't solved it either.
package eliza;
import java.io.*;
public class Eliza {
public static void main(String[] args) throws IOException {
String inputDatabase = "src/eliza/inputDataBase.txt";
String outputDatabase = "src/eliza/outputDataBase.txt";
Reader database = new Reader();
String[][] inputDB = database.Reader(inputDatabase);
String[][] outputDB = database.Reader(outputDatabase);
}
}
Here is the reader class:
package eliza;
import java.io.FileReader;
import java.io.BufferedReader;
import java.io.IOException;
public class Reader {
public String[][] Reader(String name) throws IOException {
int length = 0;
String sizeLine;
FileReader sizeReader = new FileReader(name);
BufferedReader sizeBuffer = new BufferedReader(sizeReader);
while((sizeLine = sizeBuffer.readLine()) != null) {
length++;
}
String[][] database = new String[length][1];
return (database);
}
}
Here's a photo of my directory. I even put these text files in the "eliza" root folder: here
Any ideas?
Since you are using an IDE, you need to give the complete canonical path. It should be
String inputDatabase = "C:\\Users\\Tommy\\Desktop\\Eliza\\src\\eliza\\inputDataBase.txt";
String outputDatabase = "C:\\Users\\Tommy\\Desktop\\Eliza\\src\\eliza\\outputDataBase.txt";
The IDE is probably executing the bytecode from its bin folder and cannot find the relative reference.
give the exact path like
String inputDatabase = "c:/java/src/eliza/inputDataBase.txt";
you have not given the correct path, Please re check
try
{BASE_PATH}+ "Eliza/src/inputDataBase.txt"
The source directory tree isn't generally present during execution, so files that are required at runtime shouldn't be put there ... unless you're going to use them as resources, in which case their pathname is relative to the package root, and does not begin with 'src', and the data is accessed by a getResourceXXX() method, not via a FileInputStream.

Eclipse shows errors when i write information in xml file

I use the JDOM library. When I write information into an xml file, Eclipse shows errors. The system cannot find the path specified. I try to create the file in the "language" folder. How can I create the folder automatically when I write info into this file? I think the error is in this line:
FileWriter writer = new FileWriter("language/variants.xml");
Here is my code:
package test;
import java.io.FileWriter;
import java.util.LinkedList;
import org.jdom2.Attribute;
import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.output.Format;
import org.jdom2.output.XMLOutputter;
class Test {
private LinkedList<String> variants = new LinkedList<String>();
public Test() {
}
public void write() {
Element variantsElement = new Element("variants");
Document myDocument = new Document(variantsElement);
int counter = variants.size();
for(int i = 0;i < counter;i++) {
Element variant = new Element("variant");
variant.setAttribute(new Attribute("name",variants.pop()));
variantsElement.addContent(variant);
}
try {
FileWriter writer = new FileWriter("language/variants.xml");
XMLOutputter outputter = new XMLOutputter();
outputter.setFormat(Format.getPrettyFormat());
outputter.output(myDocument,writer);
writer.close();
}
catch(java.io.IOException exception) {
exception.printStackTrace();
}
}
public LinkedList<String> getVariants() {
return variants;
}
}
public class MyApp {
public static void main(String[] args) {
Test choice = new Test();
choice.write();
}
}
Here is the error:
java.io.FileNotFoundException: language\variants.xml (The system cannot find the path specified)
at java.io.FileOutputStream.open(Native Method)
at java.io.FileOutputStream.<init>(FileOutputStream.java:212)
at java.io.FileOutputStream.<init>(FileOutputStream.java:104)
at java.io.FileWriter.<init>(FileWriter.java:63)
at test.Test.write(MyApp.java:31)
at test.MyApp.main(MyApp.java:49)`enter code here
As the name suggests FileWriter is for writing to file. You need to create the directory first if it doesnt already exist:
File theDir = new File("language");
if (!theDir.exists()) {
boolean result = theDir.mkdir();
// Use result...
}
FileWriter writer = ...
For creating directories you need to use mkdir() of File class.
Example:
File f = new File("/home/user/newFolder");
f.mkdir();
It returns a boolean: true if directory created and false if it failed.
mkdir() also throws Security Exception if security manager exists and it's checkWrite() method doesn't allow the named directory to be created.
PS: Before creating directory, you need to validate if this directory already exists or not by using exists() which also returns boolean.
Regards...
Mr.777

calling an exe file inside jar

I am trying to call the "dspdf.exe" inside the jar file where this smartpdf class exists. I plan to extract it to a temp location and delete when program ends. However this doesn't seem to work, any help will be appreciated.
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import org.omg.CORBA.portable.InputStream;
public class smartpdf {
static String url="";
static String output="output.pdf";
public static void main(String[] args) throws IOException{
gui mygui = new gui();//gui will call the generate function when user selects
}
public static void generate() throws IOException{
InputStream src = (InputStream) smartpdf.class.getResource("dspdf.exe").openStream();
File exeTempFile = File.createTempFile("dspdf", ".exe");
FileOutputStream out = new FileOutputStream(exeTempFile);
byte[] temp = new byte[32768];
int rc;
while((rc = src.read(temp)) > 0)
out.write(temp, 0, rc);
src.close();
out.close();
exeTempFile.deleteOnExit();
Runtime.getRuntime().exec(exeTempFile.toString()+" "+url+" "+output );
//Runtime.getRuntime().exec("dspdf "+url+" "+output);
}
}
EDIT:
The error that I am getting:
Microsoft Windows XP [Version 5.1.2600]
(C) Copyright 1985-2001 Microsoft Corp.
Exception in thread "main" java.lang.reflect.InvocationTargetException
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.eclipse.jdt.internal.jarinjarloader.JarRsrcLoader.main(JarRsrcLoa
der.java:56)
Caused by: java.lang.ClassCastException: sun.net.www.protocol.jar.JarURLConnecti
on$JarURLInputStream cannot be cast to org.omg.CORBA.portable.InputStream
at smartpdf.generate(smartpdf.java:18)
at smartpdf.main(smartpdf.java:14)
... 5 more
You use the wrong InputStream. Change it to java.io.InputStream.
Why do you use org.omg.CORBA.portable.InputStream instead of a java.io.BufferedInputStream`
with as parameters the inputstream from the resource. I mean this:
BufferedInputStream inputstream = new BufferedInputStream(smartpdf.class.getResourceAsStream(...));
The same for your fileoutput stream: BufferedOutputStream
Don't use
class.getResource(...).openStream();
but use
class.getResourceAsStream(...);
Note also (once you've resolved the InputStream issue) that you should be consuming your spawned process stdout and stderr, otherwise the spawned process may block. See this answer for more details.

Categories