executing a dynamically created file - java

import java.io.*;
public class Demo{
public static void main(String[] args){
File f = new File("abc.txt") ;
try{
System.setOut(new PrintStream( new FileOutputStream(f) ) ) ;
}
catch(FileNotFoundException fnfe){
System.out.println(fnfe.getMessage()) ;
}
System.out.println("Hello\n") ;
try{
//throwing exception,
//is there any method to close the f File,
//before we try to open the file referred by f.
Process p = Runtime.getRuntime().exec(f.getPath()) ;
}
catch(IOException io){
System.out.println(io.getMessage()) ;
}
}
}
and the content of abc.txt after executing Demo is:-
Hello
Cannot run program "abc.txt": CreateProcess error=32, The process cannot access the file because it is being used by another process
how to avoid the exception.....
as many people here suggested, i have tried the following code,
but sadly, even that is also throwing excption....:-(
import java.io.*;
class Demo{
public static void main(String[] args){
File f = new File("abc.txt") ;
FileOutputStream fos = null ;
try{
fos = new FileOutputStream(f) ;
}
catch(FileNotFoundException fnfe){
System.out.println(fnfe.getMessage()) ;
}
PrintStream ps = new PrintStream(fos) ;
ps.println("Hello") ;
try{
fos.close() ;
//throwing exception again
Process p = Runtime.getRuntime().exec(f.getAbsolutePath()) ;
}
catch(IOException io){
System.out.println(io.getMessage()) ;
}
}
}
??????????

I am assuming that the reason for calling Runtime.getRuntime().exec(f.getPath()); is to open up the abc.txt file in a text editor. It would be better to provide complete command for opening the text editor along with the file path. I tried this with notepad.exe (windows) and it worked.
import java.io.*;
public class Demo{
public static void main(String[] args){
File f = new File("abc.txt") ;
try{
System.setOut(new PrintStream( new FileOutputStream(f) ) ) ;
}
catch(FileNotFoundException fnfe){
System.out.println(fnfe.getMessage()) ;
}
System.out.println("Hello\n") ;
try{
Process p = Runtime.getRuntime().exec("notepad.exe " + f.getPath()) ;
}
catch(IOException io){
System.out.println(io.getMessage()) ;
}
}
}
Following code dynamically generates java code and uses javac to compile it
import java.io.*;
public class Demo{
public static void main(String[] args){
File f = new File("Abc.java") ;
PrintWriter writer = null;
BufferedReader reader = null;
InputStream pStream = null;
try{
// Open File Stream and write code
writer = new PrintWriter( new FileOutputStream(f) );
String javaCode = "public class Abc { \r\n" +
"public static void main(String[] args) {\r\n" +
"System.out.println(\"Hello World!\");\r\n" +
"}\r\n" +
"}\r\n";
writer.println(javaCode) ;
writer.close();
// Run Javac to compile the code
Process p = Runtime.getRuntime().exec("javac " + f.getPath()) ;
p.waitFor();
// status = 0 => Process executed without errors
// = 1 => Process executed with errors
int status = p.exitValue();
if( status == 0 )
{
pStream = p.getInputStream();
}
else
{
pStream = p.getErrorStream();
}
// Display the output from the process
reader = new BufferedReader(new InputStreamReader(pStream));
String ln = null;
while( (ln = reader.readLine()) != null )
{
System.out.println(ln);
}
}
catch(Exception ex){
System.out.println(ex.getMessage()) ;
}
finally{
try{
if( writer != null ){writer.close();}
if( pStream != null ){pStream.close();}
if( reader != null ){reader.close();}
}
catch(Exception ex){
System.out.println(ex.getMessage()) ;
}
}
}
}

Close the file before executing it (and don't redirect System.out):
f = new File("abc.txt");
FileOutputStream fos = new FileOutputStream(f);
// You would likely use fos.write instead, but here we go
PrintStream ps = new PrintStream(fos);
ps.println("Hello\n");
fos.close();
Process p = Runtime.getRuntime().exec(f.getPath());

Close the FileOutputStream (or PrintStream) before you try to execute it.

What your program has created is a text file, not an executable file. An executable file is a binary file (or in some cases a script with a special header) which the operating system knows how to execute. I'm not sure what you expect should happen when you execute a text file whose contents are "Hello\n".
You are redirecting stdout (standard out) to your file. Later, you printed the exception stack trace to stdout, which is why the trace appears in your file. It would probably make more sense for you to write to the file directly, instead of redirecting stdout.

assuming you are running on windows, instead of
Process p = Runtime.getRuntime().exec(f.getPath());
you could use
Process p = Runtime.getRuntime().exec("start " + f.getPath());
which should choose whatever application you have associated with .txt files.

Related

FileNotFoundException, but file exists in the same level

I've created a program, which helds the grades of the pupils, I want to store these grades in a txt file, and when I start the program, import the grades and after the program finished, export the grades. I have the import and exportTo methods in a separate file, and then I call these methods in the main class. All files are on the same level and there are no syntax errors. But I still get a FileNotFoundException as an error. Here's my import and export code:
public void exportTo(String fileName) {
try (
FileOutputStream fos = new FileOutputStream(fileName);
PrintWriter writer = new PrintWriter(fos);
) {
for (Grade grade : mGrades) {
System.out.printf("New grade" +grade);
writer.printf("%s|%s%n",grade.getPupil(), grade.getGrade());
}
} catch(IOException ioe) {
System.out.printf("Problem saving %s %n", fileName);
ioe.printStackTrace();
}
}
public void importFrom(String fileName) {
try (
FileInputStream fis = new FileInputStream(fileName);
BufferedReader reader = new BufferedReader(new InputStreamReader(fis));
) {
String line;
while((line = reader.readLine()) != null) {
String[] args = line.split("\\|");
addGrade(new Grade(args[0], args[1]));
}
} catch(IOException ioe) {
System.out.printf("Problems loading %s %n", fileName);
ioe.printStackTrace();
}
}
It has to do with the fact that your working directory is not set correctly. To get around this issue, do this.
'''
System.setProperty("user.dir", YOUR_WORKING_DIRECTORY);
String dir = System.getProperty("user.dir")
'''
Then you can pass in the directory name to your function.
Or if you are using IntelliJ,
Click on 'Run'
Go to 'Edit Configurations'
Look for the 'Working directory' field
Change that to the directory you are working on.

Java code to remove initial lines of a file executing very slow

I have written java code to remove initial characters from a file with 200k records , the file is removing the initial characters but its reading the file line by line and removing the characters .The program is executing very slow . Any tweaks could be made to below code to execute it faster ?
The program is executing and writing the output to a file , but its very slow
import java.io.*;
import java.util.Scanner;
public class truncate {
public static void main(String [] args) {
// The name of the file to open.
String inputfile = "C:\\Program Files\\eclipse\\twfiles.txt";
String outputfile = "C:\\Program Files\\eclipse\\rename.txt";
// This will reference one line at a time
String line = "";
int number_of_char_to_erased =19;
try {
// FileReader reads text files in the default encoding.
FileReader fileReader =
new FileReader(inputfile);
// Always wrap FileReader in BufferedReader.
BufferedReader bufferedReader =
new BufferedReader(fileReader);
while((line = bufferedReader.readLine()) != null) {
System.out.println(line);
File input = new File(inputfile);
Scanner scan = new Scanner(input);
File output = new File(outputfile);
PrintStream print = new PrintStream(output);
while (scan.hasNext()) {
line = scan.nextLine();
line = line.substring(number_of_char_to_erased);
print.println(line);
}
scan.close();
print.close();
}
// Always close files.
bufferedReader.close();
}
catch(FileNotFoundException ex) {
System.out.println(
"Unable to open file '" +
inputfile + "'");
}
catch(IOException ex) {
System.out.println(
"Error reading file '"
+ inputfile + "'");
// Or we could just do this:
// ex.printStackTrace();
}
}
}
What appears to be the issue here is that you just created a buffered reader to read the file. Then, it reads the first line of the file. Then, you create a Scanner to read ALL the lines in the file, omitting certain characters. Then your BufferedReader reads the next line in the file. And the process repeats itself. So all you have to do is this:
File output = new File(outputfile);
PrintStream print = new PrintStream(output);
while((line = bufferedReader.readLine()) != null) {
print.println(line.substring(number_of_char_to_erased);
}
print.close();
This should much faster. Basically, since you've already allocated line to the read line from the file, you can simply print out that line, minus the number of chars, to the output file. The entire for loop with scanner was entirely unnecessary, and closing and opening the print stream for each line was also unnecessary.
EDIT: Removed the println statement since it would slow it down a bit.
Try this (Scanner and Println removed, output file refactored outside the loop):
import java.io.*;
public class truncate {
public static void main(String [] args) {
// The name of the file to open.
String inputfile = "C:\\Program Files\\eclipse\\twfiles.txt";
String outputfile = "C:\\Program Files\\eclipse\\rename.txt";
// This will reference one line at a time
String line = "";
int number_of_char_to_erased =19;
try {
// FileReader reads text files in the default encoding.
FileReader fileReader = new FileReader(inputfile);
// Always wrap FileReader in BufferedReader.
BufferedReader bufferedReader = new BufferedReader(fileReader);
File output = new File(outputfile);
PrintStream print = new PrintStream(output);
while((line = bufferedReader.readLine()) != null) {
String trimmedLine = line.substring(number_of_char_to_erased);
print.println(trimmedLine);
}
// Always close files.
bufferedReader.close();
print.close();
}
catch(FileNotFoundException ex) {
System.out.println(
"Unable to open file '" +
inputfile + "'");
}
catch(IOException ex) {
System.out.println(
"Error reading file '"
+ inputfile + "'");
// Or we could just do this:
// ex.printStackTrace();
}
}
}

How to store text lines from and arraylist into a .txt file?

I have ran into a problem with my program. The bellow method is the part of my program that is suppose to store the text lines stored in ArrayList into a text file (e.g store.txt) what am I doing wrong here? The program compiles but it does not store the text lines in to the said file. Bellow is the said method that is suppose to store the text lines
// this part stores the string into a file
static void storeTextLinesToFile(List<String> listOfTextLines, String fileName) {
try {
PrintWriter outputFile = new PrintWriter(new FileWriter(
"C:/Users/Asus/Desktop/zing/store.txt/" + fileName));
for (String line : listOfTextLines) {
outputFile.println(line);
}
outputFile.close();
} catch (IOException ioException) {
System.out.println("\n\n Cannot write to file \"" + fileName + "\"");
}
}
Try this. It's runnable code. It shows the code you have above works fine. I just changed the file path. I'm running from NetBeans so the file ends up in the Project Root folder.
ProjectRoot
src
build
store.txt
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
public class StoreToFIle {
public static void main(String[] args) {
List<String> list = new ArrayList<>();
for (int i = 0; i < 20; i++) {
list.add(String.valueOf(i));
}
storeTextLinesToFile(list, "store.txt");
}
static void storeTextLinesToFile(List<String> listOfTextLines, String fileName) {
try {
PrintWriter outputFile = new PrintWriter(new FileWriter(fileName));
for (String line : listOfTextLines) {
outputFile.println(line);
}
outputFile.close();
} catch (IOException ioException) {
System.out.println("\n\n Cannot write to file \"" + fileName + "\"");
}
}
}
Use printStackTrace() in catch block. Then only you know the absolute error of your program.
and look here.
PrintWriter output_file = new PrintWriter( new FileWriter( "C:/Users/Asus/Desktop/zing/store.txt/" + given_file_name ) ) ;
Suppose store.txt is a file instead of directory, then you will get FileNotFoundException.
So try like this..
PrintWriter output_file = new PrintWriter( new FileWriter( "C:/Users/Asus/Desktop/zing/" + given_file_name ) ) ;
Give value to given_file_name as "store.txt"

Delete Temp File in Java

Am having the below code , creating a Temp file and read that and deleting the file.
But after deletion also file available to read .Please help to find wrong with my code....
public static void main(String args[]) throws Exception
{
Calendar mSec = Calendar.getInstance();
String fileName="hubname_"+"msgname_"+mSec.getTimeInMillis();
String str ="Hello How are you doing .......";
System.out.println("fileName :"+fileName);
File f = File.createTempFile(fileName, ".xml");
FileWriter fw = new FileWriter(f);
fw.write(str);
fw.flush();
fw.close();
printFileContent(f);
f.delete();
printFileContent(f);
}
public static void printFileContent(File f)throws Exception
{
BufferedReader reader = new BufferedReader( new FileReader(f));
String line = null;
StringBuilder stringBuilder = new StringBuilder();
String ls = System.getProperty("line.separator");
while( ( line = reader.readLine() ) != null ) {
stringBuilder.append( line );
stringBuilder.append( ls );
}
System.out.println("stringBuilder.toString() :"+stringBuilder.toString());
}
Output :
fileName :hubname_msgname_1358655424194
stringBuilder.toString() :Hello How are you doing .......
stringBuilder.toString() :Hello How are you doing .......
You should close reader in printFileContent. File.delete cannot delete an opened file (at least on Windows, see Keith Randall's comment below) in which case it returns false. You could check if delete was successful
if (!f.delete()) {
throw new IOException("Cannot delete " + f);
}
The following comment was added to File.delete API in Java 7
Note that the Files class defines the delete method to throw an IOException when a file cannot be deleted. This is useful for error reporting and to diagnose why a file cannot be deleted.
public static void printFileContent(File f)throws Exception
{
BufferedReader reader = new BufferedReader( new FileReader(f));
String line = null;
StringBuilder stringBuilder = new StringBuilder();
String ls = System.getProperty("line.separator");
while( ( line = reader.readLine() ) != null ) {
stringBuilder.append( line );
stringBuilder.append( ls );
}
System.out.println("stringBuilder.toString() :"+stringBuilder.toString());
if(reader != null){
reader.close();
}
}

How to write float values to a text file in Java

I am reading files from a GRD file:
File stockInputFile = new File("C://MAX.GRD");
I want to write them to a text file:
File StockOutputFile = new File("C://StockOut.txt");
Am getting some Korean letters. Can you please help me in coding?
Actually I want to store them as float numbers into a text file .. I am able to do the same with C.
fin = fopen("D:\\DailyT\\MeanT\\MEAN.GRD","rb"); // Input file
fout = fopen("D:\\DailyT\\MEAN.TXT","w"); // Output file
fread(&t,sizeof(t),1,fin) ;
for(i=0 ; i < 32 ; i++)
{
fprintf(fout,"\n") ;
for(j=0 ; j < 35 ; j++)
fprintf(fout,"%6.2f",t[i][j]);
}
In Java, writing to a file goes like this:
import java.io.*;
class FileWrite
{
public static void main(String args[])
{
try{
// Create file
FileWriter fstream = new FileWriter("out.txt");
BufferedWriter out = new BufferedWriter(fstream);
out.write("Hello Java");
//Close the output stream
out.close();
} catch (Exception e) {
System.err.println("Error: " + e.getMessage());
}
}
}
See Google to get more tutorials about "java write to file" and "java read from file". Also please update your question once you have actually tried something and met with some difficulty.

Categories