I want to send the input of a jar from one file and save the output in another,
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
List<String> builder = new ArrayList<>();
String line;
while (!(line = sc.nextLine()).isBlank()) {
builder.add(line);
}
builder.stream().sorted().forEach(System.out::println);
sc.close();
}
when I execute the jar I try it like this
java -jar name.jar > output.txt < input.txt
but it generates the exception java.util.NoSuchElementException, I appreciate any help.
This is what I believe is the easiest way to accomplish what you are trying to do:
public static void main(String[] args) throws IOException {
FileWriter fw = new FileWriter("output.txt"); // Used to write to output.txt
Scanner sc = new Scanner(System.in);
List<String> builder = new ArrayList<>();
while (sc.hasNextLine()) { // Same thing as what you had, just 1 less line
// Not entirely sure what you're trying to do here;
//if no input is given at the EXACT time the program is run, this will be skipped
builder.add(sc.next());
}
builder.stream().sorted().forEach((s) -> { // Changed this to a lambda
System.out.println(s);
try {
fw.write(s);
} catch (IOException e) {
e.printStackTrace();
}
});
fw.close();
sc.close();
}
The easiest way would be to pass your input.txt file as a parameter to your jar. You can then utilize Files.readAllLines to read your text file and do your sort and then send each line to std out
Then you can redirect std out to your output.txt file.
public static void main(String[] args) throws IOException {
if (args == null || args.length == 0) throw new RuntimeException("No file provided");
Path file = Paths.get(args[0]);
if (Files.notExists(file)) throw new IOException(args[0] + " cannot be found.");
Files.readAllLines(file).stream().sorted().forEach(System.out::println);
}
Then you can invoke it like this:
java -jar name.jar input.txt > output.txt
The code is okay, not perfect, but it works. Of course your class needs to have some more lines (like defining the import and class definition etc.), but you only posted the main method is and that's okay for me.
At runtime, you're piping < input.txt as your standard input which is great.
I think your problem could be:
Your input.txt contains nothing, then you'll get this exception
Or the input.txt is in a different directory at runtime, so you're actually not piping anything as an input. There's no error from the command line, but this way you get the exception too.
One of those could be the cause.
Related
Well, I might have flooded my title a bit but I can't get my java program to find input.txt so I can actually do something with it
This is for homework, I've been trying for the past few hours to get the code to recognize input.txt. I've put "/input.txt" and stuff before just in case, it still didn't work.
0
Output
import java.io.*;
import java.util.Scanner;
public class DataProcessor {
public static void main(String args[]) throws FileNotFoundException {
int[] answers = {0,0,0,0};
File file=new File("input.txt");
Scanner scan=new Scanner(file);
while (scan.hasNextLine()) {
String letter = scan.nextLine();
if (letter.equals("a")) {
answers[0] = answers[0]++;
} else {
if (letter.equals("b")) {
answers[1] = answers[1]++;
} else {
if (letter.equals("c")) {
answers[2] = answers[2]++;
} else {
if (letter.equals("d")) {
answers[3] = answers[3]++;
}
}
}
}
}
System.out.println(answers[0]);
}
}
I expect it to be able to read the file so that I can run the rest of the code, but none of it's working. What am I doing wrong here? It's just been so frustrating. What's supposed to happen is I make an output.txt file but I can't get to that part until I stop it from throwing errors and not reading the input
No longer throwing errors, but is still not reading the file, or something?
File objects do not have a hasNextLine or nextLine method.
Also, you might want to learn about else if () statements and that == should never be used to compare strings.
Scanner scan=new Scanner(file);
while (scan.hasNextLine()) {
String line = scan.nextLine();
if (line.equals("a")) {
answers[0] = answers[0]++;
} else if (line.equals("b")) {
answers[1] = answers[1]++;
} else if (...) {
// ...
}
}
Suggestion: Using in IDE like Eclipse or IntelliJ will highlight your errors before you try to compile.
And Scanner objects generally aren't preferred over BufferedReader - https://stackoverflow.com/a/5868528/2308683
I'm attempting to pass a File object to the Scanner constructor.
File file = new File("in.txt");
try{
Scanner fileReader = new Scanner(file);
}
catch(Exception exp){
System.out.println(exp.getMessage());
}
I have an in.txt in the root of the project, src and bin directories in case I'm getting the location wrong. I have tried giving absolute paths as well. This line
Scanner fileReader = new Scanner(file);
always fails. Execution jumps to the end of main. If I misspell the name of the file, I get a FileNotFoundException. I'm on an Ubuntu 12.10 Java 1.7 with OpenJDK
I am running on linux and this is how you need to do it
import java.io.File;
import java.io.IOException;
import java.util.Scanner;
public class Testing {
public static void main(String args[]) throws IOException {
Scanner s = null;
try {
//notice the path is fully qualified path
s = new Scanner(new File("/tmp/one.txt"));
while (s.hasNext()) {
System.out.println(s.next());
}
} finally {
if (s != null) {
s.close();
}
}
}
}
here is the result :
source from Java Docs
If you do: File file = new File("in.txt"); in your java program
(let's assume it is named Program.java) then the file in.txt should
be in the working directory of your program at runtime. So if you
run your program like this:
java Program
or
java package1.package2.Program
and you are in /test1/test2/ when running this command,
then the file in.txt needs to be in /test1/test2/.
I have in my code a hardcoded name for a text file I am reading.
String fileName = "test.txt";
However I now have to use a command argument like so:
text.java arg1 arg2 arg3 (can be any amount) < test.txt
Can anyone help me please?
I have it getting the arguments no problem just not sure on the file. Thank you
I have tried:
String x = null;
try {
BufferedReader f = new BufferedReader(new InputStreamReader(System.in));
while( (x = f.readLine()) != null )
{
System.out.println(x);
}
}
catch (IOException e) {e.printStackTrace();}
System.out.println(x);
}
However my application now hangs on readLine, any ideas for me to try please?
That is because the file is not passed as an argument, but piped as standard input.
If that is the intended use (to pipe the content of the file), then you just have to read it from System.in (in means standard input):
public static void main(String[] args) throws IOException {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
String firstLine = in.readLine();
// etc.
}
If you just wanted to pass the file name, then you have to remove or escape that <, because it means "pipe" in shell.
Pass the file as filename to your program and then open this file and read from it.
I'm using Scanner to read a file with different extension that a text file normally has but with same content as text file.
If I do use Scanner on text.txt extension then I do get out put but when I perform same task on the different extension but with same content that I don't get any output at all.
After performing different test, it seen that the problem are those characters: “ ”
Any clue why same file with different extension got different behaviors?
file:
“1 line”
2nd line
3 rd line
code:
public static void main(String[] args)
{
String path = "C:\\Users\\user\\Documents\\t1.RANDOM";
File file = new File(path);
StringBuilder sb = new StringBuilder();
try {
Scanner sc = new Scanner(file);
while(sc.hasNextLine())
{
sb.append(sc.nextLine()+"\n");
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
System.out.println(sb);
}
I might think Scanner is doing different stream reading if it doesn't identify a known extension.
Maybe try using the following constructor:
Scanner sc = new Scanner(file, "UTF-8");
import java.io.*;
import java.util.*;
public class Readfilm {
public static void main(String[] args) throws IOException {
ArrayList films = new ArrayList();
File file = new File("filmList.txt");
try {
Scanner scanner = new Scanner(file);
while (scanner.hasNext())
{
String filmName = scanner.next();
System.out.println(filmName);
}
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
}}
Above is the code I'm currently attempting to use, it compiles fine, then I get a runtime error of:
java.util.NoSuchElementException
at java.util.Scanner.throwFor(Scanner.java:907)
at java.util.Scanner.next(Scanner.java:1416)
at Readfilm.main(Readfilm.java:15)
I've googled the error and not had anything that helped (I only googled the first 3 lines of the error)
Basically, the program I'm writing is part of a bigger program. This part is to get information from a text file which is written like this:
Film one / 1.5
Film two / 1.3
Film Three / 2.1
Film Four / 4.0
with the text being the film title, and the float being the duration of the film (which will have 20 minutes added to it (For adverts) and then will be rounded up to the nearest int)
Moving on, the program is then to put the information in an array so it can be accessed & modified easily from the program, and then written back to the file.
My issues are:
I get a run time error currently, not a clue how to fix? (at the moment I'm just trying to read each line, and store it in an array, as a base to the rest of the program) Can anyone point me in the right direction?
I have no idea how to have a split at "/" I think it's something like .split("/")?
Any help would be greatly appreciated!
Zack.
Your code is working but it reads just one line .You can use bufferedReader here is an example import java.io.*;
class FileRead
{
public static void main(String args[])
{
try{
// Open the file that is the first
// command line parameter
FileInputStream fstream = new FileInputStream("textfile.txt");
// Get the object of DataInputStream
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());
}
}
}
And here is an split example class StringSplitExample {
public static void main(String[] args) {
String st = "Hello_World";
String str[] = st.split("_");
for (int i = 0; i < str.length; i++) {
System.out.println(str[i]);
}
}
}
I wouldn't use a Scanner, that's for tokenizing (you get one word or symbol at a time). You probably just want to use a BufferedReader which has a readLine method, then use line.split("/") as you suggest to split it into two parts.
Lazy solution :
Scanner scan = ..;
scan.nextLine();