how can i Merge files - java

How can i wright in the beggining of the first file infomation which contains in second file, so that they merge each other?? please help, thanks.
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
FileInputStream fileReader = new FileInputStream(reader.readLine());
FileOutputStream fileWriter = new FileOutputStream(reader.readLine(), true);
while (fileReader.available() > 0) {
int data = fileReader.read();
fileWriter.write(data);
}
fileReader.close();
fileWriter.close();
reader.close();

This can be done in pure Java...
It reads the second file and appends to the first file.
Keep in mind, that this will not work for large files, since it saves all of fileA content into memory.
Scanner reader = new Scanner(System.in);
System.out.println("Enter the first file path");
String fileA = reader.next();
System.out.println("Enter the second file path");
String fileB = reader.next();
try {
// Read from and cache fileA
StringBuilder cache = new StringBuilder();
BufferedReader readerA = new BufferedReader(new FileReader(new File(fileA)));
String line = null;
while((line = readerA.readLine()) != null) {
cache.append(line);cache.append("\n");
}
readerA.close();
// Read from fileB and overwrite to fileA
FileWriter writerB = new FileWriter(new File(fileA));
BufferedReader readerB = new BufferedReader(new FileReader(new File(fileB)));
line = null;
while((line = readerB.readLine()) != null) {
writerB.write(line);writerB.write("\n");
}
writerB.close();
readerB.close();
// Append original fileA content back into fileA
FileWriter writerA = new FileWriter(new File(fileA), true);
writerA.write(cache.toString());
writerA.close();
} catch (Exception e) {
e.printStackTrace();
}

Simply use
org.apache.commons.io.FileUtils.copyFile(srcFile, destFile);
//rename the file names if needed
OR you can use SequenceInputStream to create a sequence of multiple input stream.
Sample code:
File srcFile = new File("resources/abc.txt");
File destFile = new File("resources/xyz.txt");
File temp = new File("resources/temp.txt");
try {
FileInputStream fileInputStream1 = new FileInputStream(srcFile);
FileInputStream fileInputStream2 = new FileInputStream(destFile);
SequenceInputStream inputStream = new SequenceInputStream(fileInputStream1,
fileInputStream2);
FileOutputStream outputStream = new FileOutputStream(temp);
byte[] buffer = new byte[1024];
int read = -1;
while ((read = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, read);
}
inputStream.close();
outputStream.close();
fileInputStream1.close();
fileInputStream2.close();
// here you can rename the temp file or delete a source file if needed
} catch (IOException e) {
e.printStackTrace();
}

Related

Read complete file without looping in android

i need a solution for reading a text file which was stored in internal storage.
i don't want to read it line by line. without use looping how to read a complete text file and store it into a string.
BufferedReader br;
String line;
String data = "";
// String text="";
try {
br = new BufferedReader(new FileReader(new File(Environment.getExternalStorageDirectory(), "queue_mgr.txt")));
while ((line = br.readLine()) != null) {
sb.append(line);
}
br.close();
}
You can use a large byte buffer and gain some efficiency:
try
{
InputStream in = new FileInputStream (from);
OutputStream out = new FileOutputStream (to);
// Transfer bytes from in to out
byte[] buf = new byte[1024 * 10]; // 5MB would be about 500 iterations
int len;
while ((len = in.read (buf)) > 0)
out.write (buf, 0, len);
in.close ();
out.close ();
}
}
catch (FileNotFoundException e)
{
...
}
catch (IOException e)
{
...
}

Java append new column to csv file

I want to calculate some column data and write it to csv file as column. Then after calculating other column of data I want to append it to same file but as new column.
Here is what I did:
try {
FileWriter writer = new FileWriter(OUT_FILE_PATH, true);
for (int i=0; i<data.size(); i++) {
writer.append(String.valueOf(data.get(i)));
writer.append(",");
writer.append("\n");
}
writer.flush();
writer.close();
} catch (Exception e) {}
Result - It appends the new column below the first column, so I have single long column.
Thanks,
Something like this perhaps:
public void appendCol(String fileName, ???ArrayList??? data) { //assuming data is of type ArrayList here, you need to be more explicit when posting code
String lineSep = System.getProperty("line.separator");
String output = "";
try{
BufferedReader br = new BufferedReader(new FileReader(fileName));
String line = null;
int i = 0;
while ((line = br.readLine()) != null) {
output += line.replace(
lineSep,
"," + String.valueOf(data.get(i)) + lineSep);
i++;
}
br.close();
FileWriter fw = new FileWriter(fileName, false); //false to replace file contents, your code has true for append to file contents
fw.write(output);
fw.flush();
fw.close();
} catch (Exception e){
e.printStackTrace();
}
}
You will have to read your file (line by line) and then insert the new column to every line. Here's a solution using BufferedReader and BufferedWriter
public void addColumn(String path,String fileName) throws IOException{
BufferedReader br=null;
BufferedWriter bw=null;
final String lineSep=System.getProperty("line.separator");
try {
File file = new File(path, fileName);
File file2 = new File(path, fileName+".1");//so the
//names don't conflict or just use different folders
br = new BufferedReader(new InputStreamReader(new FileInputStream(file))) ;
bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file2)));
String line = null;
int i=0;
for ( line = br.readLine(); line != null; line = br.readLine(),i++)
{
String addedColumn = String.valueOf(data.get(i));
bw.write(line+addedColumn+lineSep);
}
}catch(Exception e){
System.out.println(e);
}finally {
if(br!=null)
br.close();
if(bw!=null)
bw.close();
}
}
I have used apache-commons for resolving this issue. There was no perfect answer that worked for me. After a lot of effort, this worked for me.
Writer writer = Files.newBufferedWriter(Paths.get("output.csv"));
CSVPrinter csvPrinter = new CSVPrinter(writer, CSVFormat.DEFAULT
//add whichever column you want in withHeader
.withHeader("createdTs", "destroyedTs", "channelName", "uid", "suid", "did", "joinTs", "leaveTs", "platform", "location", "consumption"));
//actual columns in your passed CSV
String[] HEADERS = {"createdTs", "destroyedTs", "channelName", "uid", "suid", "did", "joinTs", "leaveTs", "platform", "location"};
Reader in = new FileReader(yourCsvFile);
Iterable<CSVRecord> records = CSVFormat.DEFAULT
.withHeader(HEADERS)
.withFirstRecordAsHeader()
.parse(in);
for (CSVRecord row : records) {
String tempValue = String.valueOf(Long.parseLong(row.get("leaveTs")) - Long.parseLong(row.get("joinTs")));
csvPrinter.printRecord(row.get("createdTs"), row.get("destroyedTs"),row.get("channelName"), row.get("uid"),
row.get("suid"), row.get("did"), row.get("joinTs"), row.get("leaveTs"),
row.get("platform"), row.get("location"), tempValue);
}
Hope this will help you.
{
//CREATE CSV FILE
StringBuffer csvReport = new StringBuffer();
csvReport.append("header1,Header2,Header3\n");
csvReport.append(value1 + "," + value2 + "," + value3 + "\n");
generateCSVFile( filepath,fileName, csvReport); // Call the implemented mathod
}
public void generateCSVFile(String filepath,String fileName,StringBuffer result)
{
try{
FileOutputStream fop = new FileOutputStream(filepath);
// get the content in bytes
byte[] contentInBytes = result.toString().getBytes();
fop.write(contentInBytes);
fop.flush();
//wb.write(fileOut);
if(fop != null)
fop.close();
}catch (Exception ex)
{
ex.printStackTrace();
}
}

Corrupted file while manipulating files

Hello i am trying to manipulate a file(copying temp to orig.) but it seems that there is a problem (access is denied) whenever i try to open transaction_sales.dat file for the second time. What should I do? :(((
public static void writeFile() {
Path file = null;
Path file2 = null;
OutputStream output = null;
BufferedWriter writer = null;
InputStream input = null;
BufferedReader reader = null;
String[] strReaderAssign = new String[10000]; // for reading files
String strReader = null;
int strike = 0; // counter
try { // UNFINISHED
file = Paths.get("transaction_sales.dat");
output = new BufferedOutputStream(Files.newOutputStream(file, CREATE));
writer = new BufferedWriter(new OutputStreamWriter(output));
input = new BufferedInputStream(Files.newInputStream(file));
reader = new BufferedReader(new InputStreamReader(input));
if(reader.readLine() == null) { // if file is empty
writer.write(strHolder, 0, strHolder.length()); // writes to file
writer.close(); // closes file
reader.close(); // closes read file
}
else { // write to temporary file
file = Paths.get("transaction_sales.dat");
file2 = Paths.get("transaction_sales_temp.dat"); // temporary file
output = new BufferedOutputStream(Files.newOutputStream(file2));
writer = new BufferedWriter(new OutputStreamWriter(output));
writer.write((strHolder), 0, strHolder.length()); // writes to temp file
for(int i = 0; i < 10; i++) {
writer.newLine(); // writes new line to file 10x
}
writer.close(); // closes file
try {
file = Paths.get("transaction_sales.dat"); // re-reads updated data in a file
input = new BufferedInputStream(Files.newInputStream(file));
reader = new BufferedReader(new InputStreamReader(input));
while((strReader = reader.readLine()) != null) {
strReaderAssign[strike] = strReader; // assigns to array
strike++; // increment
}
strike = 0; // resets value
reader.close(); // closes file
// appends file
output = new BufferedOutputStream(Files.newOutputStream(file2, APPEND));
writer = new BufferedWriter(new OutputStreamWriter(output));
for(int j = 0; (strReaderAssign[j] != null); j++) {
writer.write(strReaderAssign[j]);
writer.newLine();
}
// resets value
for(int j = 0; j < strReaderAssign.length; j++) {
strReaderAssign[j] = null;
}
writer.close(); // closes file
file = Paths.get("transaction_sales.dat");
file2 = Paths.get("transaction_sales_temp.dat");
Files.copy(file2, file, REPLACE_EXISTING);
Files.delete(file);
}
catch(IOException d) {
System.out.println(d.getMessage());
}
}
}
catch(Exception e) {
System.out.println(e.getMessage());
}
}

Read and modify each files in a folder - Java [duplicate]

This question already has answers here:
How to read all files in a folder from Java?
(33 answers)
Closed 8 years ago.
I have a folder with 1000 files. Each file contains text in varied number of lines. What I want and have tried to achieve is to read 'each' file and append all the lines into 1 single line (that is, I want each file to have a single line of texts).
This is what I have tried but it only prints the names of the files without effecting any changes to the files...
String line = "";
try{
file = new FileReader(filename);
BufferedReader reader = new BufferedReader (file);
while ((line = reader.readLine()) != null){
allLine.append(line);
}
//System.out.println(allLine);
} catch (IOException e) {
throw new RuntimeException("File not found");
}
return allLine.toString();
FileWriter op = null;
op = new FileWriter(fileName);
BufferedWriter wryt = new BufferedWriter(op);
wryt.write(s);
wryt.flush();
if(op != null){
op.close();
}
File[] lOfiles = folder.listFiles();
for (int i = 0; i< lOfiles.length; i++){
if(lOfiles[i].isFile()){
System.out.println(lOfiles[i].getName());
ReadLines rd = new ReadLines();
String rw = rd.readtxtFile(lOfiles[i].toString());
rd.writetxtFile(lOfiles[i].getName(), rw);
}
}
try {
File folder = new File("yourfolderpath");
File out = new File("outputfile.txt");
try(BufferedWriter bw = new BufferedWriter(new FileWriter(out))){
for(File f: folder.listFiles()) {
BufferedReader br = new BufferedReader(new FileReader(f));
for(String line = br.readLine(); line!=null; line=br.readLine()) {
bw.write(line);
}
}
}
} catch (IOException e) {
e.printStackTrace();
}

Process binary file in Java using FileItemStream

I have a webapplication which allows to upload binary files. I have to parse them and save the content 1:1 into a String and then into the database.
When I use uuencode on a unix machine to encode the binary file, then it works. Is there a way to do this automatically in java?
if (isMultipart) {
//Create a new file upload handler
ServletFileUpload upload = new ServletFileUpload();
//Parse the request
FileItemIterator iter = upload.getItemIterator(request);
while (iter.hasNext()) {
FileItemStream item = iter.next();
String name = item.getFieldName();
InputStream stream = item.openStream();
if (!item.isFormField()) {
BufferedReader reader = new BufferedReader(new InputStreamReader(stream));
String line;
licenseString = "";
while ((line = reader.readLine()) != null) {
System.out.println(line);
// Generate License File
licenseString += line + "\n";
}
}
}
session.setAttribute("licenseFile", licenseString);
System.out.println("adding licensestring to session. ");
}
It works of course for all non-binary files uploaded. How can I extend it to support binary files?
// save to file
// =======================================
InputStream is = new BufferedInputStream(item.openStream());
BufferedOutputStream output = null;
try {
output = new BufferedOutputStream(new FileOutputStream("temp.txt", false));
int data = -1;
while ((data = is.read()) != -1) {
output.write(data);
}
} finally {
is.close();
output.close();
}
// read content of file
// =======================================
System.out.println("content of file:");
try {
FileInputStream fstream = new FileInputStream("temp.txt");
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String line;
licenseString = "";
String strLine;
while ((strLine = br.readLine()) != null) {
System.out.println(javax.xml.bind.DatatypeConverter.printBase64Binary(strLine.getBytes()));
licenseString += javax.xml.bind.DatatypeConverter.printBase64Binary(strLine.getBytes()) + "\n";
}
} catch (Exception e) {
System.err.println("Error: " + e.getMessage());
}
You could use the commons_fileupload lib (check it here : org.apache.commons.fileupload.disk.DiskFileItem is not created properly?)
The doc is here : http://commons.apache.org/fileupload/using.html
Your case is pretty well explained on the official website.
A Better way would be to write the upload to a temporary file and then handle it from there:
if (!item.isFormField()) {
InputStream stream = new BufferedInputStream(item.getInputStream());
BufferedOutputStream output = null;
try {
output = new BufferedOutputStream(new FileOutputStream(your_temp_file, false));
int data = -1;
while ((data = input.read()) != -1) {
output.write(data);
}
} finally {
input.close();
output.close();
}
}
now you have a temporary file, which is the same as the uploaded file, you can do your 'other' calculations from there.

Categories