I am trying to download a file that contains an integer from a remote machine, increase the value of the integer locally, write the new value to the same file and upload the file. I use scp. It downloads the file successfully. I use shell file for downloading and uploading processes. But I have problems with Scanner.
Here is the code:
import java.io.*;
import java.util.*;
public class shell {
public static void main(String[] args) throws IOException{
Runtime.getRuntime().exec("/home/ayyuce/Desktop/download.sh");
File f= new File("/home/ayyuce/Desktop/yeni.txt");
PrintWriter pw = new PrintWriter(f);
Scanner s= new Scanner(f);
int num=0;
if(s.hasNextLine()){
num=s.nextInt();
} else {
System.out.println("Error");
}
int increase=num++;
pw.println(increase);
Runtime.getRuntime().exec("/home/ayyuce/Desktop/upload.sh");
s.close();
pw.close();
}
}
The output is: Error
I wonder what is the problem with Scanner.
Thank you so much!
PrintWriter pw = new PrintWriter(f);
From javadoc
file - The file to use as the destination of this writer. If the
file exists then it will be truncated to zero size; otherwise, a new
file will be created. The output will be written to the file and is
buffered.
Of course, Scanner can't read anything, because the file was truncated to zero size in new PrintWriter(f).
Related
I am working on a Java program that reads a text file line-by-line, each with a number, takes each number throws it into an array, then tries and use insertion sort to sort the array. I need help with getting the program to read the text file.
I am getting the following error messages:
java.io.FileNotFoundException: 10_Random (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 insertionSort.main(insertionSort.java:14)
I have a copy of the .txt file in my "src" "bin" and main project folder but it still cannot find the file. I am using Eclipse by the way.
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class insertionSort {
public static void main(String[] args) {
File file = new File("10_Random");
try {
Scanner sc = new Scanner(file);
while (sc.hasNextLine()) {
int i = sc.nextInt();
System.out.println(i);
}
sc.close();
}
catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
You have to put file extension here
File file = new File("10_Random.txt");
Use following codes to read the file
import java.io.File;
import java.util.Scanner;
public class ReadFile {
public static void main(String[] args) {
try {
System.out.print("Enter the file name with extension : ");
Scanner input = new Scanner(System.in);
File file = new File(input.nextLine());
input = new Scanner(file);
while (input.hasNextLine()) {
String line = input.nextLine();
System.out.println(line);
}
input.close();
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
-> This application is printing the file content line by line
here are some working and tested methods;
using Scanner
package io;
import java.io.File;
import java.util.Scanner;
public class ReadFromFileUsingScanner {
public static void main(String[] args) throws Exception {
File file=new File("C:\\Users\\pankaj\\Desktop\\test.java");
Scanner sc=new Scanner(file);
while(sc.hasNextLine()){
System.out.println(sc.nextLine());
}
}
}
Here's another way to read entire file (without loop) using Scanner class
package io;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class ReadingEntireFileWithoutLoop {
public static void main(String[] args) throws FileNotFoundException {
File file=new File("C:\\Users\\pankaj\\Desktop\\test.java");
Scanner sc=new Scanner(file);
sc.useDelimiter("\\Z");
System.out.println(sc.next());
}
}
using BufferedReader
package io;
import java.io.*;
public class ReadFromFile2 {
public static void main(String[] args)throws Exception {
File file=new File("C:\\Users\\pankaj\\Desktop\\test.java");
BufferedReader br=new BufferedReader(new FileReader(file));
String st;
while((st=br.readLine())!=null){
System.out.println(st);
}
}
}
using FileReader
package io;
import java.io.*;
public class ReadingFromFile {
public static void main(String[] args) throws Exception {
FileReader fr=new FileReader("C:\\Users\\pankaj\\Desktop\\test.java");
int i;
while((i=fr.read())!=-1){
System.out.print((char) i);
}
}
}
Make sure the filename is correct (proper capitalisation, matching extension etc - as already suggested).
Use the Class.getResource method to locate your file in the classpath - don't rely on the current directory:
URL url = insertionSort.class.getResource("10_Random");
File file = new File(url.toURI());
Specify the absolute file path via command-line arguments:
File file = new File(args[0]);
In Eclipse:
Choose "Run configurations"
Go to the "Arguments" tab
Put your "c:/my/file/is/here/10_Random.txt.or.whatever" into the "Program arguments" section
No one seems to have addressed the fact that your not entering anything into an array at all. You are setting each int that is read to "i" and then outputting it.
for (int i =0 ; sc.HasNextLine();i++)
{
array[i] = sc.NextInt();
}
Something to this effect will keep setting values of the array to the next integer read.
Than another for loop can display the numbers in the array.
for (int x=0;x< array.length ; x++)
{
System.out.println("array[x]");
}
You need the specify the exact filename, including the file extension, e.g. 10_Random.txt.
The file needs to be in the same directory as the executable if you want to refer to it without any kind of explicit path.
While we're at it, you need to check for an int before reading an int. It is not safe to check with hasNextLine() and then expect an int with nextInt(). You should use hasNextInt() to check that there actually is an int to grab. How strictly you choose to enforce the one integer per line rule is up to you, of course.
private void loadData() {
Scanner scanner = null;
try {
scanner = new Scanner(new File(getFileName()));
while (scanner.hasNextLine()) {
Scanner lijnScanner = new Scanner(scanner.nextLine());
lijnScanner.useDelimiter(";");
String stadVan = lijnScanner.next();
String stadNaar = lijnScanner.next();
double km = Double.parseDouble(lijnScanner.next());
this.voegToe(new TweeSteden(stadVan, stadNaar), km);
}
} catch (FileNotFoundException e) {
throw new DbException(e.getMessage(), e);
} finally {
if(scanner != null){
scanner.close();
}
}
}
File Path Seems to be an issue here please make sure that file exists in the correct directory or give the absolute path to make sure that you are pointing to a correct file.
Please log the file.getAbsolutePath() to verify that file is correct.
You should use either
File file = new File("bin/10_Random.txt");
Or
File file = new File("src/10_Random.txt");
Relative to the project folder in Eclipse.
The file you read in must have exactly the file name you specify: "10_random" not "10_random.txt" not "10_random.blah", it must exactly match what you are asking for. You can change either one to match so that they line up, but just be sure they do. It may help to show the file extensions in whatever OS you're using.
Also, for file location, it must be located in the working directory (same level) as the final executable (the .class file) that is the result of compilation.
At first check the file address, it must be beside your .java file or in any address that you define in classpath environment variable. When you check this then try below.
you must use a file name by it's extension in File object constructor, as an example:
File myFile = new File("test.txt");
but there is a better way to use it inside Scanner object by pass the filename absolute address, as an example:
Scanner sc = new Scanner(Paths.get("test.txt"));
in this way you must import java.nio.file.Paths as well.
How does one use a specified file path rather than a file from the resource folder as an input or output stream? This is the class I have and I would like to read from a specific file path instead of placing the txt file in the resources folder in IntelliJ. Same for an output stream. Any help rendered would be appreciated thanks.
Input Stream
import java.io.*;
import java.util.*;
public class Example02 {
public static void main(String[] args) throws FileNotFoundException {
// STEP 1: obtain an input stream to the data
// obtain a reference to resource compiled into the project
InputStream is = Example02.class.getResourceAsStream("/file.txt");
// convert to useful form
Scanner in = new Scanner(is);
// STEP 2: do something with the data stream
// read contents
while (in.hasNext()) {
String line = in.nextLine();
System.out.println(line);
}
// STEP 3: be polite, close the stream when done!
// close file
in.close();
}
}
Output stream
import java.io.*;
public class Example03
{
public static void main(String []args) throws FileNotFoundException
{
// create/attach to file to write too
// using the relative filename will cause it to create the file in
// the PROJECT root
File outFile = new File("info.txt");
// convert to a more useful writer
PrintWriter out = new PrintWriter(outFile);
//write data to file
for(int i=1; i<=10; i++)
out.println("" + i + " x 5 = " + i*5);
//close file - required!
out.close();
}
}
Preferred way for getting InputStream is java.nio.file.Files.newInputStream(Path)
try(final InputStream is = Files.newInputStream(Paths.get("/path/to/file")) {
//Do something with is
}
Same for OutputStream Files.newOutputStream()
try(final OutputStream os = Files.newOutputStream(Paths.get("/path/to/file")) {
//Do something with os
}
Generally, here is official tutorial from Oracle to working with IO.
First you have to define the path you want to read the file from, absolute path like so:
String absolutePath = "C:/your-dir/yourfile.txt"
InputStream is = new FileInputStream(absolutePath);
It's similar for writing the file as well:
String absolutePath = "C:/your-dir/yourfile.txt"
PrintWriter out = new PrintWriter(new FileOutputStream(absolutePath));
You can use a file object as:
File input = new File("C:\\[Path to file]\\file.txt");
How do I read the following information from a txt file and write just the numbers to another text file using Java? I have it displaying to the console but it will not write to the file also.
Jones 369218658389641
Smith 6011781008881301
Wayne 5551066751345482
Wines 4809134775860430
Biggie 9925689541232325
Luke 7586425896325410
Brandy 4388576018410707
Ryan 2458912425860439
import java.util.Scanner;
import java.io.File;
public class test {
public static void main(String[] args) throws Exception {
// Create a File instance
java.io.File file = new java.io.File("accounts.txt");
// Create a Scanner for the file
Scanner input = new Scanner(file);
// Read data from a file
while (input.hasNext()) {
String accountName = input.next();
Long cardNumber = input.nextLong();
//this is where I want to write just the numbers to a file called cardnums.txt
file = new java.io.File("cardnums.txt");
java.io.PrintWriter output = new java.io.PrintWriter(file);
output.println(cardNumber);
System.out.println(cardNumber);
}
// Close the file
input.close();
}
}
I got it now.
import java.util.Scanner;
import java.io.File;
public class test {
public static void main(String[] args) throws Exception {
// Create a File instance
java.io.File file = new java.io.File("accounts.txt");
// Create a Scanner for the file
Scanner input = new Scanner(file);
// Read data from a file
file = new java.io.File("cardnums.txt");
java.io.PrintWriter output = new java.io.PrintWriter(file);
while (input.hasNext()) {
String accountName = input.next();
Long cardNumber = input.nextLong();
//this is where I want to write just the numbers to a file called credit.txt
output.println(cardNumber);
System.out.println(cardNumber);
}
// Close the file
input.close();
output.flush();
output.close();
}
}
java.io.PrintWriter output = new java.io.PrintWriter(file);
First of all why are you everytime calling this in loop with same filename?
Secondly, once you define it outside loop,
Call flush() on outputstream object and close if not null (preferabbly in finally block) after loop.
if(output!=null) {
output.flush();
output.close();
}
Here's a 1-liner:
Files.write(Paths.get("cardnums.txt"), () ->
Files.lines(Paths.get("accounts.txt"))
.map(s -> s.replaceAll("\\D", ""))
.collect(toList())
.iterator());
Disclaimer: Code may not compile or work as it was thumbed in on my phone (but there's a reasonable chance it will work)
So i am working on a code that receives 2 strings. The string are "input#.txt" or "output#.txt" the # symbol is replaced with whatever number file is used. Now in the input file is the information I need to get to. How do I determine if that input.txt file can be opened and how do I open it.
I've tried a buffered reader and trying to just make the string a file.
import java.util.*;
import java.io.*;
public class Robot {
public static void readInstructions(String inputFileName, String outputFileName) throws InvalidRobotInstructionException{
try{
BufferedReader input = new BufferedReader(new FileReader(inputFileName));
File inner = new File(inputFileName);
Scanner in = new Scanner(input);
PrintWriter wrt;
wrt = new PrintWriter(outputFileName);
if(input.readLine() == null){
System.out.println("Input file not found.");
return;
}
This will read a file in:
Scanner input = new Scanner(new File("input5.txt"));
Don't forget to add throws FileNotFoundException in your main method
edit: I see you added code.
I am working on a Java program that reads a text file line-by-line, each with a number, takes each number throws it into an array, then tries and use insertion sort to sort the array. I need help with getting the program to read the text file.
I am getting the following error messages:
java.io.FileNotFoundException: 10_Random (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 insertionSort.main(insertionSort.java:14)
I have a copy of the .txt file in my "src" "bin" and main project folder but it still cannot find the file. I am using Eclipse by the way.
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class insertionSort {
public static void main(String[] args) {
File file = new File("10_Random");
try {
Scanner sc = new Scanner(file);
while (sc.hasNextLine()) {
int i = sc.nextInt();
System.out.println(i);
}
sc.close();
}
catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
You have to put file extension here
File file = new File("10_Random.txt");
Use following codes to read the file
import java.io.File;
import java.util.Scanner;
public class ReadFile {
public static void main(String[] args) {
try {
System.out.print("Enter the file name with extension : ");
Scanner input = new Scanner(System.in);
File file = new File(input.nextLine());
input = new Scanner(file);
while (input.hasNextLine()) {
String line = input.nextLine();
System.out.println(line);
}
input.close();
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
-> This application is printing the file content line by line
here are some working and tested methods;
using Scanner
package io;
import java.io.File;
import java.util.Scanner;
public class ReadFromFileUsingScanner {
public static void main(String[] args) throws Exception {
File file=new File("C:\\Users\\pankaj\\Desktop\\test.java");
Scanner sc=new Scanner(file);
while(sc.hasNextLine()){
System.out.println(sc.nextLine());
}
}
}
Here's another way to read entire file (without loop) using Scanner class
package io;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class ReadingEntireFileWithoutLoop {
public static void main(String[] args) throws FileNotFoundException {
File file=new File("C:\\Users\\pankaj\\Desktop\\test.java");
Scanner sc=new Scanner(file);
sc.useDelimiter("\\Z");
System.out.println(sc.next());
}
}
using BufferedReader
package io;
import java.io.*;
public class ReadFromFile2 {
public static void main(String[] args)throws Exception {
File file=new File("C:\\Users\\pankaj\\Desktop\\test.java");
BufferedReader br=new BufferedReader(new FileReader(file));
String st;
while((st=br.readLine())!=null){
System.out.println(st);
}
}
}
using FileReader
package io;
import java.io.*;
public class ReadingFromFile {
public static void main(String[] args) throws Exception {
FileReader fr=new FileReader("C:\\Users\\pankaj\\Desktop\\test.java");
int i;
while((i=fr.read())!=-1){
System.out.print((char) i);
}
}
}
Make sure the filename is correct (proper capitalisation, matching extension etc - as already suggested).
Use the Class.getResource method to locate your file in the classpath - don't rely on the current directory:
URL url = insertionSort.class.getResource("10_Random");
File file = new File(url.toURI());
Specify the absolute file path via command-line arguments:
File file = new File(args[0]);
In Eclipse:
Choose "Run configurations"
Go to the "Arguments" tab
Put your "c:/my/file/is/here/10_Random.txt.or.whatever" into the "Program arguments" section
No one seems to have addressed the fact that your not entering anything into an array at all. You are setting each int that is read to "i" and then outputting it.
for (int i =0 ; sc.HasNextLine();i++)
{
array[i] = sc.NextInt();
}
Something to this effect will keep setting values of the array to the next integer read.
Than another for loop can display the numbers in the array.
for (int x=0;x< array.length ; x++)
{
System.out.println("array[x]");
}
You need the specify the exact filename, including the file extension, e.g. 10_Random.txt.
The file needs to be in the same directory as the executable if you want to refer to it without any kind of explicit path.
While we're at it, you need to check for an int before reading an int. It is not safe to check with hasNextLine() and then expect an int with nextInt(). You should use hasNextInt() to check that there actually is an int to grab. How strictly you choose to enforce the one integer per line rule is up to you, of course.
private void loadData() {
Scanner scanner = null;
try {
scanner = new Scanner(new File(getFileName()));
while (scanner.hasNextLine()) {
Scanner lijnScanner = new Scanner(scanner.nextLine());
lijnScanner.useDelimiter(";");
String stadVan = lijnScanner.next();
String stadNaar = lijnScanner.next();
double km = Double.parseDouble(lijnScanner.next());
this.voegToe(new TweeSteden(stadVan, stadNaar), km);
}
} catch (FileNotFoundException e) {
throw new DbException(e.getMessage(), e);
} finally {
if(scanner != null){
scanner.close();
}
}
}
File Path Seems to be an issue here please make sure that file exists in the correct directory or give the absolute path to make sure that you are pointing to a correct file.
Please log the file.getAbsolutePath() to verify that file is correct.
You should use either
File file = new File("bin/10_Random.txt");
Or
File file = new File("src/10_Random.txt");
Relative to the project folder in Eclipse.
The file you read in must have exactly the file name you specify: "10_random" not "10_random.txt" not "10_random.blah", it must exactly match what you are asking for. You can change either one to match so that they line up, but just be sure they do. It may help to show the file extensions in whatever OS you're using.
Also, for file location, it must be located in the working directory (same level) as the final executable (the .class file) that is the result of compilation.
At first check the file address, it must be beside your .java file or in any address that you define in classpath environment variable. When you check this then try below.
you must use a file name by it's extension in File object constructor, as an example:
File myFile = new File("test.txt");
but there is a better way to use it inside Scanner object by pass the filename absolute address, as an example:
Scanner sc = new Scanner(Paths.get("test.txt"));
in this way you must import java.nio.file.Paths as well.