I made the program in java to convert the text in the file in the uppercase but it erases data instead of converting it
But when I take data from 1 file and write converted data into another file, it works fine.
So I got problem that how can I do this using single file.
Here below is my code, Tell me how to correct this?
import java.io.FileReader;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.FileWriter;
public class uppercase{
public static void main(String[] args) {
try {
FileReader reader = new FileReader("e.txt");
FileWriter writer = new FileWriter("e.txt");
int data;
int data2;
while((data=reader.read())!= -1) {
data2=Character.toUpperCase(data);
writer.write(data2);
}
reader.close();
writer.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
this is bad idea, because you are writing to same file you are reading from. You should either:
Load complete file to memory, close it and then dump it to same file.
Save to different file and rename (better)
firstly you open a stream to read from file and append the result to a String variable and at the end of reading, you write all the data to the file:
try {
FileReader reader = new FileReader("e.txt");
String result = "";
int data;
int data2;
while ((data = reader.read()) != -1) {
data2 = Character.toUpperCase(data);
result += (char)data2;
}
reader.close();
System.out.println(result);
FileWriter writer = new FileWriter("e.txt");
writer.write(result);
writer.flush();
writer.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Related
I am currently trying to program a small API, but with my writeToFile method, even if I use true in the method, it deletes everything that is in the file and only writes in the text of the user (#param text).
What did I do wrong ? I tried to print the string, but it appears to be empty. If I only use the readFile method of mine, it reads out the whole file correctly.
Need help.
package at.tornaduuu.usefullapi.files;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class FileUtils {
public static void writeToFile(String text, File file, boolean keepIndexText) {
try {
String indexText = "";
FileWriter fw = new FileWriter(file);
if (keepIndexText) {
indexText = FileUtils.readFile(file);
System.out.println(indexText);
FileUtils.clearFile(file);
fw.write(indexText + text);
fw.close();
}
else {
fw.write(text);
fw.close();
}
}
catch (IOException e) {
e.printStackTrace();
}
}
public static void clearFile(File file) {
try {
FileWriter fw = new FileWriter(file);
fw.write("");
fw.close();
}
catch (IOException e) {
e.printStackTrace();
}
}
public static String readFile(File file) {
String fileIndex = "";
int unicode;
try {
FileReader fr = new FileReader(file);
try {
while ((unicode = fr.read()) != -1) {
fileIndex += (char) unicode;
}
fr.close();
}
catch (IOException e) {
e.printStackTrace();
}
}
catch (FileNotFoundException e) {
e.printStackTrace();
}
return fileIndex;
}
}
You are not appending to file, you are just rewriting it. That's because FileWriter is not set to append. You can change this:
FileWriter fw = new FileWriter(file); //rewrites file every time write() method is called
to:
FileWriter fw = new FileWriter(file,true); //append text in file when write() is called
and it should work.
You are calling FileWriter(File) which in turn will call FileOutputStream(String name, append = False). So your file is getting truncated before you read content.
There is another constructor FileWriter(File file, boolean append) that you can use with keepIndexText, in such case your FileUtils.clearFile(file); is pretty useless.
I don't know if it is possible or not, but my requirement is like - I have to read data from a file called System.evtx in my java program.
While I am doing this like simple file reading I am getting some ASCII character or I can say un-readable format.
Is there any way to solve this issues.
Thanks in advance.
This is a difficult question to answer without an example of the file content, but after some googling it seems to be a windows event log file? So im unsure about the exact format but apparently they can be converted to .csv files using powershell:
Get-WinEvent -Path c:\path\to\eventlog.evtx |Export-Csv eventlog.csv
Once its in a csv format you could simple parse them in the traditional way of csv or just split by comma's etc.
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
public class CSVReader {
public static void main(String[] args) {
String csvFile = "eventlog.csv";
BufferedReader br = null;
String line = "";
String cvsSplitBy = ",";
try {
br = new BufferedReader(new FileReader(csvFile));
while ((line = br.readLine()) != null) {
// use comma as separator
String[] line = line.split(cvsSplitBy);
for(int i=0;i<line.length;i++){
System.out.println(line[i]);
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
I really need help with Java io manipulation of Streams. I don't know why this won't show me the contents of the file. I need to be able to view the text in this binary file "Data.abc" If I can view the contents of this file, i need to create a switch case condition to display it's contents per row / column.
Everytime I run the program, it returns some weird letters and characters like � NAme Address�����
Please help. I'm new to manipulation of streams. Thanks.
package IO_ReadFile;
import java.io.*;
public class ReadFile {
public static void main(String[] args) {
InputStream istream; // creates an Input Stream and named it "istream"
OutputStream ostream; // creates an Output Stream and named it "ostream"
File inputFile = new File("Data.abc"); //passes file as argument
int c;
final int EOF=-1;
ostream = System.out;
try
{
istream = new FileInputStream(inputFile);
try
{
while((c=istream.read()) !=EOF)
ostream.write(c);
}
catch(IOException e)
{
System.out.println("Error: " + e.getMessage());
}
finally
{
try
{
istream.close();
ostream.close();
}
catch(IOException e)
{
System.out.println("File did not close");
}
}
}
catch(FileNotFoundException e)
{
System.exit(1);
}
}
}
Goal: Print the data from a .dat file to the console using Eclipse.
(Long-Term Goal): Executable that I can pass a .dat file to and it creates a new txt file with the data formatted.
The .dat: I know the .dat file contains control points that I will need to create a graph with using ECMAScript.
Eclipse Setup:
Created Java Project
New > Class .. called the Class FileRead
Now I have FileRead.java which is:
1/ package frp;
2/
3/ import java.io.BufferedReader;
4/ import java.io.File;
5/ import java.io.FileReader;
6/
7/ public class FileRead {
8/
9/ public static void main(String[] args) {
10/ FileReader file = new FileReader(new File("dichromatic.dat"));
11/ BufferedReader br = new BufferedReader(file);
12/ String temp = br.readLine();
13/ while (temp != null) {
14/ temp = br.readLine();
15/ System.out.println(temp);
16/ }
17/ file.close();
18/ }
19/
20/ }
Please note this approach was borrowed from here: https://stackoverflow.com/a/18979213/3306651
1st Challenge: FileNotFoundException on LINE 10
Screenshot of Project Explorer:
QUESTION: How to correctly reference the .dat file?
2nd Challenge: Unhandled exception type IOException LINES 12, 14, 17
QUESTION: How to prevent these exceptions?
Thank you for your time and effort to help me, I am recreating Java applets using only JavaScript. So, I'm looking to create java tools that extract data I need to increase productivity. If you are interested in phone/web app projects involving JavaScript, feel free to contact me 8503962891
1. Without changing your code, you must place the file in the project's root folder.
Otherwise, reference it as src/frp/dichromatic.dat
2. Doing something like this:
public static void main(String[] args) {
FileReader file = null;
try {
file = new FileReader(new File("dichromatic.dat"));
} catch (FileNotFoundException e1) {
System.err.println("File dichromatic.dat not found!");
e1.printStackTrace();
}
BufferedReader br = new BufferedReader(file);
String line;
try {
while ((line = br.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
System.err.println("Error when reading");
e.printStackTrace();
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
System.err.println("Unexpected error");
e.printStackTrace();
}
}
}
}
3. Creation of a new txt file "formatted". In this example, the formatting will be settings the characters to uppercase.
public static void main(String[] args) {
FileReader file = null;
BufferedWriter bw = null;
File outputFile = new File("output.formatted");
try {
file = new FileReader(new File("dichromatic.dat"));
} catch (FileNotFoundException e1) {
System.err.println("File dichromatic.dat not found!");
e1.printStackTrace();
}
try {
bw = new BufferedWriter(new FileWriter(outputFile));
} catch (IOException e1) {
System.err.println("File is not writtable or is not a file");
e1.printStackTrace();
}
BufferedReader br = new BufferedReader(file);
String line;
String lineformatted;
try {
while ((line = br.readLine()) != null) {
lineformatted = format(line);
bw.write(lineformatted);
// if you need it
bw.newLine();
}
} catch (IOException e) {
System.err.println("Error when processing the file!");
e.printStackTrace();
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
System.err.println("Unexpected error");
e.printStackTrace();
}
}
if (bw != null) {
try {
bw.close();
} catch (IOException e) {
System.err.println("Unexpected error");
e.printStackTrace();
}
}
}
}
public static String format(String line) {
// replace this with your needs
return line.toUpperCase();
}
I would strongly recommend spending some time reading through the Java Trails Tutorials. To answer your specific question, look at Lesson: Exceptions.
To oversimplify, just wrap the file-handling code in a try...catch block. By example:
package frp;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
public class FileRead {
public static void main(String[] args) {
try {
FileReader file = new FileReader(new File("dichromatic.dat"));
BufferedReader br = new BufferedReader(file);
String temp = br.readLine();
while (temp != null) {
temp = br.readLine();
System.out.println(temp);
}
file.close();
} catch (FileNotFoundException fnfe) {
System.err.println("File not found: " + fnfe.getMessage() );
} catch (IOException ioe) {
System.err.println("General IO Error encountered while processing file: " + ioe.getMessage() );
}
}
}
Note that ideally, your try...catch should wrap the smallest possible unit of code. So, wrap the FileReader separately, and "fail-fast" if the file isn't found, and wrap the readLine loop in its own try...catch. For more examples and a better explanation of how to deal with exceptions, please reference the link I provided at the top of this answer.
Edit: issue of file path
Not finding the file has to do with the location of the file relative to the root of the project. In your original post, you reference the file as "dichromatic.dat" but relative to the project root, it is in "src/frp/dichromatic.dat". As rpax recommends, either change the string that points to the file to properly reference the location of the file relative to the project root, or move the file to project root and leave the string as-is.
I was testing out writing to files with this code:
package files;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
public class FileTest1
{
public static void main(String[] args)
{
try
{
try
{
File f = new File("filetest1.txt");
FileWriter fWrite = new FileWriter(f);
BufferedWriter fileWrite = new BufferedWriter(fWrite);
fileWrite.write("This is a test!");
}
catch(FileNotFoundException e)
{
System.out.print("A FileNotFoundException occurred!");
e.printStackTrace();
}
}
catch(IOException e)
{
System.out.println("An IOException occurred!:");
e.printStackTrace();
}
}
}
Nothing happens when it is executed.
"This is a test!" is not written, nor the StackTrace or the "A/An [exception] occurred!"...
I don't know what's causing the problem. I have fileTest1.txt in the package right under the file...
A BufferedWriter does just that, it buffers the output before it is written to the destination. This can make the BufferedWriter faster to use as it doesn't have to write to a slow destination, like a disk or socket, straight away.
The contents will be written when the internal buffer is to full, you flush the Writer or close the writer
Remember, if you open it, you should close it...
For example...
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class TestFileWriter {
public static void main(String[] args) {
try {
BufferedWriter fileWrite = null;
try {
File f = new File("filetest1.txt");
System.out.println("Writing to " + f.getCanonicalPath());
FileWriter fWrite = new FileWriter(f);
fileWrite = new BufferedWriter(fWrite);
fileWrite.write("This is a test!");
fileWrite.flush();
} catch (FileNotFoundException e) {
System.out.print("A FileNotFoundException occurred!");
e.printStackTrace();
} finally {
try {
// Note, BufferedWriter#close will also close
// the parent Writer...
fileWrite.close();
} catch (Exception exp) {
}
}
} catch (IOException e) {
System.out.println("An IOException occurred!:");
e.printStackTrace();
}
try {
BufferedReader br = null;
try {
File f = new File("filetest1.txt");
System.out.println("Reading from " + f.getCanonicalPath());
FileReader fReader = new FileReader(f);
br = new BufferedReader(fReader);
String text = null;
while ((text = br.readLine()) != null) {
System.out.println(text);
}
} catch (FileNotFoundException e) {
System.out.print("A FileNotFoundException occurred!");
e.printStackTrace();
} finally {
try {
// Note, BufferedWriter#close will also close
// the parent Writer...
br.close();
} catch (Exception exp) {
}
}
} catch (IOException e) {
System.out.println("An IOException occurred!:");
e.printStackTrace();
}
}
}
If you are using Java 7, you may like to take a look at try-with-resources
After
fileWrite.write("This is a test!");
you have to flush() the writer. To avoid leaking of resources you should also close() the writer (which automatically flushes it).
So you need to add:
fileWrite.close();
Use BufferedWriter.flush() and BufferedWriter.close(). Additional info here http://docs.oracle.com/javase/7/docs/api/java/io/BufferedWriter.html
You must call close() or at least flush() on the writer in order for the buffer to be really written to the file.