I have written a simple code to write text into file but i am not able to figure out why text is not written to file. I have written a class with method which will take text file as input and create the text file if it is not exist
here is the code:
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
public class OutputFile {
public static BufferedWriter fbw = null;
public BufferedWriter createFile(String text)
{
try{
File file =new File(text);
if(!file.exists()){
file.createNewFile();
}
FileWriter writer = new FileWriter(text,true);
fbw =new BufferedWriter(writer);
}
catch (IOException e)
{
System.out.println(e.getMessage());
}
return fbw;
}
public static void main(String args[]) throws IOException
{
String resultFilePath = "C:/Users/Desktop/stringcompare/output.txt";
OutputFile file = new OutputFile();
fbw = file.createFile(resultFilePath);
fbw.write("hello");
fbw.newLine();
fbw.close();
}
}
Try this:
try(BufferedWriter bw = new BufferedWriter(new FileWriter("FILE_PATH_HERE"))){
br.write("STUFF_TO_WRITE_HERE");
} catch(IOException e){
}
With this try-with-resources statement, all of the closing file effort is done automatically.
This will only work for Java 7 or higher.
You have to flush your output. This can be done directly by calling writer.flush().
Related
I am having trouble loading data into my Java program. The program says the file exists, but FileReader is giving a FileNotFoundException. I have tried the full path and made sure all files are closed. I am using the Eclipse IDE. Any suggestions?
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.File;
public class ReadCSV {
public static void main(String[] args) {
String filepath = "/Users/mrodgers/Documents/other/languages/java/eclipse/ReadCSV/src/data.csv";
//String filepath = "~/Desktop/data.csv";
//String filepath = "data.csv";
File mjr = new File(filepath);
System.out.println(mjr.exists());
FileReader fr = new FileReader(mjr);
// BufferedReader br = new BufferedReader(fr);
}
}
This works on my machine, with the filename set to one that I have of course.
But I did have to wrap the creation of FileReader in a try/catch for FileNotFound exception -- is that what you mean? The compiler tells you that you must catch FileNotFound if you use that FileReader constructor?
Unless/until you do that, eclipse should (and does, on my machine) mark the call to the FileReader constructor as an error because that exception is not caught.
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
public class FilePlay
{
public static void main(String[] args) {
String filepath = "/Users/ralph/Documents/My Chess Database/r-b.pgn";
//String filepath = "~/Desktop/data.csv";
//String filepath = "data.csv";
File mjr = new File(filepath);
System.out.println(mjr.exists());
try
{
FileReader fr = new FileReader(mjr);
BufferedReader br = new BufferedReader(fr);
}
catch (FileNotFoundException fnf)
{
fnf.printStackTrace();
}
}
}
I am trying to convert ansii(latin-5) text file to utf-8 text file in a directory. I made a small mechanish to understand if the file is ansii or utf-8 however when i try to change ansii file to utf-8 program deletes all values in the text. Where am i doing wrong?
Thanks in advance.
Here is my code:
package altyazi;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.nio.file.Files;
import java.nio.file.Paths;
public class operation{
public static int howmany =0;
public static int howmanysmalli=0;
public static double ratio;
File myFile;
public static void koddegıstır(String myfile) throws IOException{
File file = new File(myfile);
byte[] bytesArray = new byte[(int) file.length()];
FileInputStream fis = new FileInputStream(file);
fis.read(bytesArray);
fis.close();
int[] freqs = new int[256];
for(byte b: bytesArray){
freqs[b&0x0ff]++;
}
howmany = freqs[107]+freqs[75];
howmanysmalli=freqs[253];
System.out.println("Character \"k\" appears " + howmany +" times in the text "+myfile);
ratio = (double)howmany/(double)bytesArray.length;
System.out.println("How many: "+howmany);
System.out.println("Length: "+bytesArray.length);
System.out.println("Ratio: "+ratio);
//Cp1254
if(ratio<0.01){
System.out.println("Text file is probably not turkish");
}else{
System.out.println("Text file is probably turkish");
if(howmanysmalli>20){
String line;
BufferedReader br = new BufferedReader(new InputStreamReader(
new FileInputStream(myfile),
"ISO-8859-9"));
Writer out = new BufferedWriter(
new OutputStreamWriter(new FileOutputStream(
myfile), "UTF-8"));
try {
while ((line = br.readLine()) != null) {
out.write(line);
out.write("\n");
}
} finally {
br.close();
out.close();
}
}else{
System.out.println("Passed as utf-8");
}
}
}
}
You are overwriting the file when you create the FileOutputStream. This creates an empty file. You need to write to a new file, and delete the old one and rename the new one when complete.
I have been using kafka to get and process streaming inputs and I have the source and sink properties as:
name=local-file-sink
connector.class=org.apache.kafka.connect.file.FileStreamSinkConnector
tasks.max=10
file=pnrsink5.xml
topics=test
name=local-file-source
connector.class=org.apache.kafka.connect.file.FileStreamSourceConnector
tasks.max=10
file=pnrtes.xml
topic=test
And I run the standalone as:
bin/connect-standalone.sh config/connect-standalone.properties config/connect-file-source.properties config/connect-file-sink.properties
And when I give parsed input using a java program written as:
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class parse
{
public static void main(String args[]) throws IOException
{
int count=0,c=1,a=0;
String file="/home/tthteg/speed_pnr/Source/Source_pnr.xml";
String l1="</PNR>";
String line;
try
{
FileReader fileReader=new FileReader(file);
BufferedReader bufferedReader=new BufferedReader(fileReader);
String file="/home/tthteg/speed_pnr/Source/Source_pnr.xml";
String l1="</PNR>";
String line;
try
{
FileReader fileReader=new FileReader(file);
BufferedReader bufferedReader=new BufferedReader(fileReader);
BufferedWriter bufWriter = new BufferedWriter(new FileWriter("/home/tthteg/speed_pnr/kafka/pnrtes.xml"));
try
{
while((line=bufferedReader.readLine())!=null)
{
if(c%2==0)
{
Thread.sleep(5000);
c=1;
}
if(line.contains("<PNR"))
{
c++;
System.out.println(line);
bufWriter.write(line);
while((line=bufferedReader.readLine()).equals(l1)==false)
{
System.out.println(line);
bufWriter.write(line);
}
bufWriter.write("</PNR>");
bufWriter.flush();
System.out.println("</PNR>");
count++;
a=count;
}
}
}catch(Exception e)
{
System.out.println(e);
}
bufferedReader.close();
bufWriter.flush();
System.out.println(a);
}catch (FileNotFoundException e) {
e.printStackTrace();
}
System.out.println(a);
}
}
PROBLEMS:
1.Whenever I run the java file,I have to touch the source file(echo -e >> pnrtes.xml) to get the data imported to the sink file(pnrsink5.xml)
2.I have found some data missing at the beginning(some 4 words) in the sink file.
Thank you in advance
I try to output the content of a text file. But I don't know how to work with the RandomAccessFile. I haven't found good examples at google. I hope for some help.
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
public class ReadTextFile {
public static void main(String[] args) throws IOException {
File src = new File ("C:/Users/hansbaum/Documents/Ascii.txt");
cat(src);
}
public static void cat(File quelle){
try (RandomAccessFile datei = new RandomAccessFile(quelle, "r")){
// while(datei.length() != -1){
// datei.seek(0); //
// }
} catch (FileNotFoundException fnfe) {
System.out.println("Datei nicht gefunden!");
} catch (IOException ioe) {
System.err.println(ioe);
}
}
}
related from doc
try (RandomAccessFile datei = new RandomAccessFile(quelle, "r")){
String line;
while ( (line = datei.readLine()) != null ) {
System.out.println(line);
}
System.out.println();
} catch (FileNotFoundException fnfe) {
} catch (IOException ioe) {
System.err.println(ioe);
}
What makes you think you need a RandomAccessFile? The easiest way is probably to use nio's convenience methods. With those, reading a file is as close to a one-liner as it gets in Java.
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.io.IOException;
class Test {
public static void main(String[] args) throws IOException {
List<String> lines = Files.readAllLines(Paths.get("./Test.java"), StandardCharsets.UTF_8);
for (String l: lines)
System.out.println(l);
}
}
Be aware however that this is not a good idea if you happen to work with very large files as they might not fit into memory.
Try to create Stream from FileChannel to read and write in another file out.txt like this:
try (RandomAccessFile datei = new RandomAccessFile(quelle, "r").getChannel();){
// Construct a stream that reads bytes from the given channel.
InputStream is = Channels.newInputStream(rChannel);
File outFile = new File("out.txt");
// Create a writable file channel
WritableByteChannel wChannel = new RandomAccessFile(outFile,"w").getChannel();
// Construct a stream that writes bytes to the given channel.
OutputStream os = Channels.newOutputStream(wChannel);
// close the channels
is.close();
os.close();
I asked a similar question before regarding I/O using Java.
I'm trying to copy a list of strings into another file.
package file;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class File {
public static void main(String[] args) {
FileWrite fW = new FileWrite();
try (BufferedReader br = new BufferedReader(new FileReader("B:\\inLarge.dat")))
{
String stCurrent;
while ((stCurrent = br.readLine()) != null) {
System.out.println(stCurrent);
fW.serializeAddress(stCurrent, stCurrent);
}
} catch (IOException e) {
e.printStackTrace();
}
//fW.serializeAddress("Boston", "Canada");
}
}
And
package file;
import java.io.BufferedWriter;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.ObjectOutputStream;
import java.io.PrintStream;
import java.io.Serializable;
import java.io.File;
import java.io.IOException;
public class FileWrite {
public void serializeAddress(String city, String country){
try
{
File file = new File("B:\\outLarge.txt");
if (!file.exists())
{
file.createNewFile();
}
FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
bw.write(city + " " + country);
bw.close();
System.out.println("Done");
}
catch(Exception ex)
{
ex.printStackTrace();
}
}
}
But the ending output file has only one result, how do I make it copy everything?
I am thinking buffered-writer somehow needs to be in the loop to write new ones on top of existing ones? But not sure how to implement that.
Thanks a lot.
You are overwriting the file contents every time you call your serialize method, because you didn't open the file in append mode. To prevent overwriting, open the file in append mode:
FileWriter fw = new FileWriter(file.getAbsoluteFile(), true);
However, this is one case where the solution is probably over-engineered. For efficiency you really should be opening your file just once. Here's an example:
public static void main(final String[] args) {
try {
final BufferedReader reader = new BufferedReader(new FileReader("infile.txt"));
final PrintWriter writer = new PrintWriter(new File("outfile.txt"));
String inputLine;
while((inputLine = reader.readLine()) != null) {
writer.println(inputLine);
}
reader.close();
writer.close();
} catch(final Exception e) {
e.printStackTrace();
}
}
You're overwriting the existing file every time you open it. Instead append to it.
Change
FileWriter fw = new FileWriter(file.getAbsoluteFile());
to
FileWriter fw = new FileWriter(file.getAbsoluteFile(), true);