How to write float values to a text file in Java - 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.

Related

Text is not appended in new file in attempt to make a text file manipulator

Problem and where I'm at: I can't append text into these new files I create with the program. Currently it only copies files but does not append them. See line with comment
"// append file name into the new file ".
Secondly, the final dump file seems to only append the .java file, it's not reading or appending the input files.
The explanation of what I'm trying to do:
The long and short is that I am trying to make a program that will be placed into random folders with .txt files filled with data.
I need the program to
Look within the realm of the folder it is in only
Then take any .txt file and
a) make a copy but append the original file name into the text body (at the top), inside a sub-folder like "< filenamehere.txt" into the body (at the top)
b) then copy body contents of the original.txt
c) take the prepended .txt file and append it to a single dump.txt file
d) repeat this for all local txt files and keep appending to the end of the dump.txt file
So at the end, if I had 7 files, I will have 7 appended copies and 1 giant dump file containing everything of the 7 appended copies. So for example, if I had three text files, each one having only one word in them. So a.txt, b.txt, c.txt
and the three words are "Hello world !". The a.txt copy would have the contents inside
">a.txt
Hello
"
Right now it's just copying the Hello (original body content) but not appending the >a.txt. The final dump text file is not accumulating anything from the other files, but it's strangely enough picking up the source code from the .java file. So essentially, I get a //Output folder and inside are the copies of the .txt files and a megaDump.txt that manages to pick up the .java text, but no other text files are appended.
import java.io.* ;
import java.nio.file.*;
public class FilePrepender // class name
{
public static void main (String [] args)
{
// make a giant dump file which we will append all read files into
try {
new File("Output\\").mkdirs();
File megaDumpFile = new File("Output\\masterDump.txt");
if (megaDumpFile.createNewFile()) {
System.out.println("File creation success");
} else {
System.out.println("File was not made. File already exists. Please delete");
}
} catch (IOException e) {
}
//grab file names
File folder = new File(".");
File[] listOfFiles = folder.listFiles();
for (int i = 0; i < listOfFiles.length; i++) {
if (listOfFiles[i].isFile()) {
listOfFiles[i].getName();
} else if (listOfFiles[i].isDirectory()) {
//do nothing
}
}
//open files + duplicate + prepend + and append product to end of master dump file
// main for
for (int j = 0; j < listOfFiles.length; j++){
//append file name for mega dump file
String fileNameTemp = listOfFiles[j].getName(); // get file name
try {
PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("Output//masterDump.txt", true)));
out.println(fileNameTemp);
out.flush();
out.close();
}
catch (IOException e) {
}
// duplicate input files
FileInputStream instream = null;
FileOutputStream outstream = null;
try {
File infile =new File(""+listOfFiles[j].getName());
File outfile =new File("Output\\"+listOfFiles[j].getName());
instream = new FileInputStream(infile);
outstream = new FileOutputStream(outfile);
byte[] buffer = new byte[1024];
int length;
// apend file name into the new file
// String fileNameTemp = listOfFiles[j].getName(); // get file name
try {
PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("Output//masterDump.txt", true)));
out.println(">"+fileNameTemp);
out.flush();
out.close();
}
catch (IOException e) {
}
// now copy contents of previous file into the new file
/*copying the contents from input stream to
* output stream using read and write methods
*/
while ((length = instream.read(buffer)) > 0){
outstream.write(buffer, 0, length);
}
//Closing the input/output file streams
instream.close();
outstream.close();
// file is copied
} catch(IOException ioe) {
}
// copy newly copied file into mega dump
try {
File infile =new File("Output\\"+listOfFiles[j]); // newly copied
File outfile =new File("Output\\masterDump.txt");
instream = new FileInputStream(infile);
outstream = new FileOutputStream(outfile);
byte[] buffer = new byte[1024];
int length;
/*copying the contents from input stream to
* output stream using read and write methods
*/
while ((length = instream.read(buffer)) > 0){
outstream.write(buffer, 0, length);
}
//Closing the input/output file streams
instream.close();
outstream.close();
// file is copied
} catch(IOException ioe) {
}
} // end for loop
} // end main
} // end class
There are quite a few issues here:
You use for your file paths sometimes slash, sometimes 2 backslashes and sometimes even double slashes which resulted in problems at least on my Mac. Just use regular forward slashes.
The code did not filter for .txt files yet, so everything which was in the current directory was processed - even the executing program itself.
Currently the code wrote the > sometext.txt lines directly into your masterDump.txt instead of indirectly through your file copies.
The code overwrote masterDump.txt for each iteration of the loop as the file was not opened in appending mode.
Following is the code which currently produces the following result when called in a folder with a.txt, b.txt and c.txt containing "Hello", "World" and "!" respectively. I hope this is the desired behavior.
Note that there is much to improve in this code, especially handling the errors as already pointed out in the comments.
import java.io.* ;
import java.nio.file.*;
public class FilePrepender // class name
{
public static void main (String [] args)
{
// make a giant dump file which we will append all read files into
try {
new File("Output/").mkdirs();
File megaDumpFile = new File("Output/masterDump.txt");
if (megaDumpFile.createNewFile()) {
System.out.println("File creation success");
} else {
System.out.println("File was not made. File already exists. Please delete");
}
} catch (IOException e) {
}
//grab file names
File folder = new File(".");
File[] listOfFiles = folder.listFiles();
for (int i = 0; i < listOfFiles.length; i++) {
if (listOfFiles[i].isFile()) {
listOfFiles[i].getName();
} else if (listOfFiles[i].isDirectory()) {
//do nothing
}
}
//open files + duplicate + prepend + and append product to end of master dump file
// main for
for (int j = 0; j < listOfFiles.length; j++){
//append file name for mega dump file
String fileNameTemp = listOfFiles[j].getName(); // get file name
if (!fileNameTemp.toLowerCase().endsWith(".txt")) {
continue;
}
// duplicate input files
FileInputStream instream = null;
FileOutputStream outstream = null;
try {
File infile =new File(""+listOfFiles[j].getName());
File outfile =new File("Output/"+listOfFiles[j].getName());
instream = new FileInputStream(infile);
byte[] buffer = new byte[1024];
int length;
// apend file name into the new file
// String fileNameTemp = listOfFiles[j].getName(); // get file name
outstream = new FileOutputStream(outfile);
PrintWriter out = new PrintWriter(outstream);
out.println(">"+fileNameTemp);
out.flush();
out.close();
// now copy contents of previous file into the new file
/*copying the contents from input stream to
* output stream using read and write methods
*/
outstream = new FileOutputStream(outfile, true);
while ((length = instream.read(buffer)) > 0){
outstream.write(buffer, 0, length);
}
//Closing the input/output file streams
instream.close();
outstream.close();
// file is copied
} catch(IOException ioe) {
}
// copy newly copied file into mega dump
try {
File infile =new File("Output/"+listOfFiles[j]); // newly copied
File outfile =new File("Output/masterDump.txt");
instream = new FileInputStream(infile);
outstream = new FileOutputStream(outfile, true);
byte[] buffer = new byte[1024];
int length;
/*copying the contents from input stream to
* output stream using read and write methods
*/
while ((length = instream.read(buffer)) > 0){
outstream.write(buffer, 0, length);
}
//Closing the input/output file streams
instream.close();
outstream.close();
// file is copied
} catch(IOException ioe) {
}
} // end for loop
} // end main
} // end class
Agreeing with others: You delete your progress every time you 'touch' your masterDump file.
Here is my version:
import java.io.* ;
import java.nio.file.*;
public class FilePrepender // class name
{
public static void main (String [] args)
{
//Generates the string for the output for the right PC.
String OUTFILE="Output"+File.separator+"masterDump.txt";
// make a giant dump file which we will append all read files into
try {
new File("Output").mkdirs();
File megaDumpFile = new File(OUTFILE);
megaDumpFile.createNewFile();
} catch (IOException e) {
System.out.println("Something weird occured!");
}
File folder = new File(".");
// FileFilter filter = new istext();
// File[] listOfFiles = folder.listFiles( filter );
//grab file names
File[] listOfFiles = folder.listFiles();
try {
FileOutputStream fout = new FileOutputStream ( new File(OUTFILE));
PrintWriter pout = new PrintWriter( fout );
for (int j = 0; j < listOfFiles.length; j++){
//Hacky fix cause java is hard:
if ( ! listOfFiles[j].getName().endsWith(".txt")) { continue ; }
//append file name for mega dump file
pout.println(listOfFiles[j].getName()); // Append File-name
pout.flush(); //Probably a better way than this, but eh.
//Copy the file's text
Files.copy(listOfFiles[j].toPath(), fout);
fout.flush(); //Again, eh.
}
pout.close();
pout.close();
}
catch (IOException e) {
}
}
}
/* Ugh, IDK how to java. (This is the non-hacky way, but idk how to.)
public class istext implements FileFilter {
public static void accept(File pathname){
return( pathname.getName().endsWith(".txt"));
}
}
*/

How can I read a text file from the terminal and save the output to another file in java?

Hey all I'm fairly new to this but I want to not hardcode a file to be read in but I want to read it in from the terminal/command prompt. Here is what I have so far, I'm hardcoding the filename in bufferedWriter but how can I make it to where I can do a command such as (java main < in.txt > out.txt). Thanks in advance.
public static void main(String[] args) {
String inFile = "in.txt";
String outFile = "out.txt";
if (args.length > 1) {
inFile = args[0];
outFile = args[1];
}
Lexer lexer = new Lexer(inFile);
try {
BufferedWriter writer = new BufferedWriter(new FileWriter(outFile));
Token t;
while ((t = lexer.nextToken()) != null) {
writer.write(t.toString());
writer.newLine();
}
writer.close();
System.out.println("Done tokenizing file: " + inFile);
System.out.println("Output written in file: " + outFile);
} catch (IOException e) {
e.printStackTrace();
}
}
You don't, the OS handles the IO redirection with java main < in.txt > out.txt. Instead you read from System.in and write to System.out. Alternatively, based on the code you posted you might run it with
java main in.txt out.txt
Then your program would receive "in.txt" as args[0] and "out.txt" as args[1].
Read from System.in and write to System.out - also remember anything you write to System.out will be written to the file. such as Done tokenizing file: + inFile

how to set and take in a integer to/from a file in java

So this is a very simple question. I have been trying to research it, and yes I have slightly found some answers but i can't find out how it works so i have come to this.
I am making a simple game in java (pong) and their is a high score integer that i would like to be able save and load from a file (I have heard a lot about using a txt file so probably that, but i have also heard about using a xml i believe is what it is, but i did not look into that as much). How exactly do i program this?
Thank you to all who answer.
PS
I have looked into this code but I don't understand how it's workings
String strFilePath = "C://FileIO//WriteInt.txt";
try {
//create FileOutputStream object
FileOutputStream fos = new FileOutputStream(strFilePath);
DataOutputStream dos = new DataOutputStream(fos);
int i = 100;
dos.writeInt(i);
dos.close();
} catch (IOException e) {
System.out.println("IOException : " + e);
}
The most simplest way is to create a file, i.e.
write the score to a file, e.g.
String user = "John";
int score = 100;
f = new BufferedWriter(new FileReader(filepath));
f.write(user + "=" + score); // assuming "=" is not inside the user name
f.close();
then read from the file when you need it, e.g.
f = new BufferedReader(new FileReader(filepath));
String line = f.readLine().trim();
String[] temp = line.split("="); // now temp is of the form ["John", "100"]
String user = temp[0];
int score = Integer.parseInt(temp[1]);
f.close();
I think you can solve this encoding the object into a file,but it wont be an xml, it will be a custom file that only your app will be able to open
public void save(Integer ... integersToEncode){
try{
ObjectOutputStream output = new ObjectOutputStream(new FileOutputStream (new File(/*yourFileName*/)));
for(Integer encoding : integersToEncode)
output.writeObject(encoding);
output.close();
}
catch(Exception e){
//What do you want to do if the program could not write the file
}
}
For reading
public Integer[] read(int size){
Integer[] objects = new Integer[size];
try{
ObjectInputStream input = new ObjectInputStream(new FileInputStream (new File(/*yourFileName*/)));
for(int i = 0; i < size ; i++)
objects[i] = (Integer)input.readObject();
input.close();
}
catch(Exception e){
//What do you want to do if the program could not write the file
}
return objects;
}
Maybe you were confused by the way the original code you posted was printing the char 'd' to the output file. This is the character's ASCII value, as you may know. The following modifications to your code make it work the way you were orginally looking at:
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
public class Game {
public static void main(String[] args) throws IOException {
Game game = new Game();
game.writeHighScore();
}
public void writeHighScore() throws IOException{
String strFilePath = "C:/Users/User/workspace/HighScore.txt";
FileInputStream is = null;
DataInputStream dis = null;
FileOutputStream fos = null;
DataOutputStream dos = null;
try
{
//create FileOutputStream object
fos = new FileOutputStream(strFilePath);
dos = new DataOutputStream(fos);
int i = 100;
dos.writeInt(i);
System.out.println("New High Score saved");
dos.close();
// create file input stream
is = new FileInputStream(strFilePath);
// create new data input stream
dis = new DataInputStream(is);
// available stream to be read
while(dis.available()>0)
{
// read four bytes from data input, return int
int k = dis.readInt();
// print int
System.out.print(k+" ");
}
}catch(Exception e){
// if any error occurs
e.printStackTrace();
}finally{
// releases all system resources from the streams
if(is!=null)
is.close();
if(dis!=null)
dis.close();
if(fos!=null)
fos.close();
if(dos!=null)
dos.close();
}
}
}

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"

executing a dynamically created file

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.

Categories