Appending multiple files into one - java

I have 4 different files in some locations like:
D:\1.txt
D:\2.txt
D:\3.txt and
D:\4.txt
I need to create a new file as NewFile.txt, It should contains all the contents present in the above files 1.txt, 2.txt,3.txt 4.txt.......
All Data should present in the New Single file(NewFile.txt)..
Please suggest me some idea to do the same in java or Groovy....

Here's one way to do it in Groovy:
// Get a writer to your new file
new File( '/tmp/newfile.txt' ).withWriter { w ->
// For each input file path
['/tmp/1.txt', '/tmp/2.txt', '/tmp/3.txt'].each { f ->
// Get a reader for the input file
new File( f ).withReader { r ->
// And write data from the input into the output
w << r << '\n'
}
}
}
The advantage of doing it this way (over calling getText on each of the source files) is that it will not need to load the entire file into memory before writing its contents out to newfile. If one of your files was immense, the other method could fail.

This is in groovy
def allContentFile = new File("D:/NewFile.txt")
def fileLocations = ['D:/1.txt' , 'D:/2.txt' , 'D:/3.txt' , 'D:/4.txt']
fileLocations.each{ allContentFile.append(new File(it).getText()) }

i am showing you the way it is to be done in java:
public class Readdfiles {
public static void main(String args[]) throws Exception
{
String []filename={"C:\\WORK_Saurabh\\1.txt","C:\\WORK_Saurabh\\2.txt"};
File file=new File("C:\\WORK_Saurabh\\new.txt");
FileWriter output=new FileWriter(file);
try
{
for(int i=0;i<filename.length;i++)
{
BufferedReader objBufferedReader = new BufferedReader(new FileReader(getDictionaryFilePath(filename[i])));
String line;
while ((line = objBufferedReader.readLine())!=null )
{
line=line.replace(" ","");
output.write(line);
}
objBufferedReader.close();
}
output.close();
}
catch (Exception e)
{
throw new Exception (e);
}
}
public static String getDictionaryFilePath(String filename) throws Exception
{
String dictionaryFolderPath = null;
File configFolder = new File(filename);
try
{
dictionaryFolderPath = configFolder.getAbsolutePath();
}
catch (Exception e)
{
throw new Exception (e);
}
return dictionaryFolderPath;
}
}
tell me if you have any doubts

I tried solving this and i found its quite easy if you copy the contents to an array and write the array to a different file
public class Fileread
{
public static File read(File f,File f1) throws FileNotFoundException
{
File file3=new File("C:\\New folder\\file3.txt");
PrintWriter output=new PrintWriter(file3);
ArrayList arr=new ArrayList();
Scanner sc=new Scanner(f);
Scanner sc1=new Scanner(f1);
while(sc.hasNext())
{
arr.add(sc.next());
}
while(sc1.hasNext())
{
arr.add(sc1.next());
}
output.print(arr);
output.close();
return file3;
}
/**
*
* #param args
* #throws FileNotFoundException
*/
public static void main(String[] args) {
try
{
File file1=new File("C:\\New folder\\file1.txt");
File file2=new File("C:\\New folder\\file2.txt");
File file3=read(file1,file2);
Scanner sc=new Scanner(file3);
while(sc.hasNext())
System.out.print(sc.next());
}
catch(Exception e)
{
System.out.printf("Error :%s",e);
}
}
}

You can do something like this in Java. Hope it helps you resolve your problem:
import java.io.*;
class FileRead {
public void readFile(String[] args) {
for (String textfile : args) {
try{
// Open the file that is the first
// command line parameter
FileInputStream fstream = new FileInputStream(textfile);
// Get the object of DataInputStream
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine;
//Read File Line By Line
while ((strLine = br.readLine()) != null) {
// Print the content on the console
System.out.println (strLine);
// Write to the new file
FileWriter filestream = new FileWriter("Combination.txt",true);
BufferedWriter out = new BufferedWriter(filestream);
out.write(strLine);
//Close the output stream
out.close();
}
//Close the input stream
in.close();
}catch (Exception e){//Catch exception if any
System.err.println("Error: " + e.getMessage());
}
}
}
public static void main(String args[]) {
FileRead myReader = new FileRead();
String fileArray[] = {"file1.txt", "file2.txt", "file3.txt", "file4.txt"};
myReader.readFile(fileArray);
}
}

One liner example:
def out = new File(".all_profiles")
['.bash_profile', '.bashrc', '.zshrc'].each {out << new File(it).text}
OR
['.bash_profile', '.bashrc', '.zshrc'].collect{new File(it)}.each{out << it.text}
Tim's implementation is better if you have big files.

public static void main(String[] args) throws IOException {
List<String> files=new ArrayList<String>();
for(int i=10;i<14;i++)
files.add("C://opt/Test/test"+i+".csv");
String destFile ="C://opt/Test/test.csv";
System.out.println("TO "+destFile);
long st=System.currentTimeMillis();
mergefiles(files, destFile);
System.out.println("DONE."+(st-System.currentTimeMillis()));
}
public static void mergefiles(List<String> files,String destFile){
Path outFile = Paths.get(destFile);
try(FileChannel out=FileChannel.open(outFile, StandardOpenOption.CREATE, StandardOpenOption.WRITE)) {
for(String file:files) {
Path inFile=Paths.get(file);
System.out.println(inFile);
try(FileChannel in=FileChannel.open(inFile, StandardOpenOption.READ)) {
for(long p=0, l=in.size(); p<l; )
p+=in.transferTo(p, l-p, out);
}catch (IOException e) {
System.out.println("ERROR:: "+e.getMessage());
}
out.write(ByteBuffer.wrap("\n".getBytes()));
}
} catch (IOException e) {
System.out.println("ERROR:: "+e.getMessage());
}
}

Related

Pass in file text into hashmap

I am having a bit of an issues trying to pass in a file read by my program and sorted accordantly. I am not used to working with files, and i ran out of ideas as to how this could be achieved.
/////////////////////////////////////// class reads file ///////////////////////////////////
import java.io.*;
public class InFileReader {
private BufferedReader inputStream = null;
private String fileLine;
private StringBuilder sb;
public String getFile(File fileRead) throws FileNotFoundException,
IOException {
inputStream = new BufferedReader(new FileReader(fileRead)); //reads files
sb = new StringBuilder();
while((fileLine = inputStream.readLine()) != null){//keep reading lines in file till there is none
sb.append(fileLine).append("\n");
}
return sb.toString(); //returns StringBuffer read values in String form
}
}
///////////////////////////////////////////////////// end of read file class ///////////////////////
public void getFile(File fileRead) throws FileNotFoundException,
IOException {
try {
String input = fileReader.getFile(fileRead.getAbsoluteFile());
HashMap<Integer, Thing.Ship> hashmap = new HashMap<>();
while (!input.isEmpty()) { // as long as there is data in the file keep looping
Scanner sc = new Scanner(input); // scan file
if (!input.startsWith("//")) { // take out "//" from directory
String type = "";
if (sc.hasNext()) { // if there are character lines get next line
type = sc.next();
}
if (type.equalsIgnoreCase("port")) { // looks for "port"
world.assignPort(new Thing.SeaPort(sc)); // assigns value to Seaport
} else if (type.equalsIgnoreCase("dock")) {
world.assignDock(new Thing.Dock(sc));
} else if (type.equalsIgnoreCase("ship")) {
Thing.Ship s = new Thing.Ship(sc);
hashmap.put(s.getIndex(), s);
world.assignShip(s);
} else if (type.equalsIgnoreCase("pship")) {
Thing.Ship s = new Thing.PassengerShip(sc);
hashmap.put(s.getIndex(), s);
world.assignShip(s);
} else if (type.equalsIgnoreCase("cship")) {
Thing.Ship s = new Thing.CargoShip(sc);
hashmap.put(s.getIndex(), s);
world.assignShip(s);
} else if (type.equalsIgnoreCase("person")) {
world.assignPerson(new Thing.Person(sc));
}
}
}
//inputOut.setText(type);
inputOut.setText(world.toString());
} catch (Exception e) {
System.out.println(e + "-----");
}
}
Here fileRead knows where to find the file to be read "C:\Users\abe\IdeaProjects\CreateSeaPortDataFile\src\text.txt"
public void getFile(File fileRead) throws FileNotFoundException,
IOException {
this is where things just fall apart:
String input = fileReader.getFile(fileRead.getAbsoluteFile());
My intent here is to pass the location of the file so that the getFile class can read it and then be sorted into the hashmap.
again i am not familiar with how to work with file, any suggestion or comment would be greatly appreciated.
thank you in advanced.
If you get a FileNotFoundException then the file was not found.
You say the filename was "C:\Users\abe\IdeaProjects\CreateSeaPortDataFile\src\text.txt".
If you type that name in the code you must escape the backslash:
"C:\\Users\\abe\\IdeaProjects\\CreateSeaPortDataFile\\src\\text.txt".

Java File.renamTo not working

I have made the code which renames all the jpg files in a directory from 1 to n (number of files)..
if there were let say 50 jpg files that after running the program all the files are renamed to 1.jpg ,2.jpg and so on till 50.jpg
But i am facing the problem if I manually rename the file let say 50.jpg to aaa.jpg then again running the program doesn't rename that file
I have wasted one day to resove that issue
Kindly help me
Code:
public class Renaming {
private static String path; // string for storing the path
public static void main(String[] args) {
FileReader fileReader = null; // filereader for opening the file
BufferedReader bufferedReader = null; // buffered reader for buffering the data of file
try{
fileReader = new FileReader("input.txt"); // making the filereader object and paasing the file name
bufferedReader = new BufferedReader(fileReader); //making the buffered Reader object
path=bufferedReader.readLine();
fileReader.close();
bufferedReader.close();
}
catch (FileNotFoundException e) { // Exception when file is not found
e.printStackTrace();
}
catch (IOException e) { // IOException
e.printStackTrace();
}
finally {
File directory=new File(path);
File[] files= directory.listFiles(); // Storing the all the files in Array
int file_counter=1;
for(int file_no=0;file_no<files.length;file_no++){
String Extension=getFileExtension(files[file_no]); //getting the filw extension
if (files[file_no].isFile() && (Extension .equals("jpg")|| Extension.equals("JPG"))){ // checking that if file is of jpg type then apply renaming // checking thaat if it is file
File new_file = new File(path+"\\"+files[file_no].getName()); //making the new file
new_file.renameTo(new File(path+"\\"+String.valueOf(file_no+1)+".jpg")); //Renaming the file
System.out.println(new_file.toString());
file_counter++; // incrementing the file counter
}
}
}
}
private static String getFileExtension(File file) { //utility function for getting the file extension
String name = file.getName();
try {
return name.substring(name.lastIndexOf(".") + 1); // gettingf the extension name after .
} catch (Exception e) {
return "";
}
}`
first of all, you should use the path separator / . It's work on Windows, Linux and Mac OS.
This is my version of your problem to rename all files into a folder provide. Hope this will help you. I use last JDK version to speed up and reduce the code.
public class App {
private String path = null;
public static int index = 1;
public App(String path){
if (Files.isDirectory(Paths.get( path ))) {
this.path = path;
}
}
public void rename() throws IOException{
if ( this.path != null){
Files.list(Paths.get( this.path ))
.forEach( f ->
{
String fileName = f.getFileName().toString();
String extension = fileName.replaceAll("^.*\\.([^.]+)$", "$1");
try {
Files.move( f ,Paths.get( this.path + "/" + App.index + "." + extension));
App.index++;
} catch (IOException e) {
e.printStackTrace();
}
}
);
}
}
public static void main(String[] args) throws IOException {
App app = new App("c:/Temp/");
app.rename();
}
}

I want to split textfile into mutilple text files

Hi I have Text file having some tag based data and i want to split into multiple text files.
Main Text files having data like this:
==========110CYL067.txt============
<Entity Text>Cornell<Entity Type>Person
<Entity Text>Donna<Entity Type>Person
<Entity Text>Sherry<Entity Type>Person
<Entity Text>Goodwill<Entity Type>Organization
==========110CYL068.txt============
<Entity Text>Goodwill Industries Foundation<Entity Type>Organization
<Entity Text>Goodwill<Entity Type>Organization
NOTE: Over here 110CYL068.txt and 110CYL067.txt are text files.
I want to split this file into 110CYL068.txt and 110CYL067.txt and so on.
This ============ pattern is fixed.Between ============ FileName ============
file name could be anything.does anyone have any insight.
I don't want to write codes for you, so you can read the file using a BufferedReader or FileReader. You can create and write to a new File using any file writer whenever you see a line starting with ======= or containing .txt.
If you encounter those close the previous file and repeat the process.
Done ppl way to complicatet just did it fast and dirty.
public static List<String> lines = new ArrayList<String>();
public static String pattern = "==========";
public static void main(String[] args) throws IOException {
addLines(importFile());
}
private static List<String> importFile() throws FileNotFoundException, IOException {
BufferedReader br = new BufferedReader(new FileReader("C:\\temp\\test.txt"));
try {
StringBuilder sb = new StringBuilder();
String line = br.readLine();
while (line != null) {
lines.add(line.replaceFirst(pattern, ";") + "\n");
line = br.readLine();
}
} finally {
br.close();
}
return lines;
}
private static void addLines(List<String> list) throws IOException {
String FilesString = list.toString();
System.out.println(FilesString);
String[] FilesArray = FilesString.split(";");
for (String string : FilesArray) {
createFile(string);
}
}
private static void createFile(String content) throws IOException {
String[] Lines = content.replaceAll("=", "").split("\n");
File file = new File("C:\\temp\\" + Lines[0]);
file.createNewFile();
FileWriter writer = new FileWriter(file);
Lines[0] = null;
for (String Line : Lines) {
if (Line != null) {
writer.append(Line.replace(",", "")+"\n");
}
}
writer.flush();
writer.close();
}
}
Also quick and dirty, not using regex. I don't really recommend doing it like this because the for loop in main is quite confusing and could break, but it might be beneficial to use this for ideas.
import java.io.*;
import java.util.*;
class splitFiles {
public static void main(String[] args){
try {
List<String> fileRead = readFiles("some.txt");
for(int i=0; i<fileRead.size(); i++){
if(fileRead.get(i).charAt(0) == '='){
PrintWriter writer = new PrintWriter(getFileName(fileRead.get(i)), "UTF-8");
for(int j=i+1; j<fileRead.size(); j++){
if(fileRead.get(j).charAt(0) == '='){
break;
} else {
writer.println(fileRead.get(j));
}
}
writer.close();
}
}
} catch (Exception e){
}
}
public static String getFileName(String fileLine){
String[] split = fileLine.split("=");
for(String e: split){
if(e.isEmpty()){
continue;
} else {
return e;
}
}
return "No file name found";
}
public static ArrayList<String> readFile(String path){
try {
Scanner s = new Scanner(new File(path));
ArrayList<String> list = new ArrayList<String>();
while(s.hasNext()){
list.add(s.next());
}
s.close();
return list;
} catch (FileNotFoundException f){
System.out.println("File not found.");
}
return null;
}
static List<String> readFiles(String fileName) throws IOException {
List<String> words = new ArrayList<String>();
BufferedReader reader = new BufferedReader(new FileReader(fileName));
String line;
while ((line = reader.readLine()) != null) {
words.add(line);
}
reader.close();
return words;
}
}

JAVA Replacing line or strings in textfile not working

So i have made two methods that creates the file (createFile(); and one to fill the textfile with empty highscores if none are set.
public class HighscoreList {
static String highscore = null;
static PuzzleModel theModel;
static File file = null;
public static int nom;
public static int tu;
public static int nor;
public static String search = " ";
static String replace = "2";
static String numberOfRows = null;
static String timeUsed = " ";
static String numberOfMoves = " ";
public static void main(String[] args) {
createFile();
isEmptySetEmptyHighscore();
// checkScore(0);
getHighscore(0);
}
public static void createFile() {
file = new File("C:\\Users\\Thomas\\Eclipse Workspace\\15Puzzle\\15Puzzle\\src\\FifteenPuzzle\\ScoreBoard.txt");
System.out.println("Created file " + file.getName());
if (!file.exists()) {
System.out.println("File didn't exist creating new file");
try {
file.createNewFile();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public static void isEmptySetEmptyHighscore() {
try {
BufferedReader br = new BufferedReader(new FileReader(
"C:\\Users\\Thomas\\Eclipse Workspace\\15Puzzle\\15Puzzle\\src\\FifteenPuzzle\\ScoreBoard.txt"));
if (br.readLine() == null) {
setEmptyHighscoreFile();
}
} catch (IOException e) {
e.printStackTrace();
}
}
public static void setEmptyHighscoreFile() {
try {
FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
System.out.println("File is empty, fills with empty fields");
for (int i = 3; i < 101; i++) {
bw.write(i + ":" + numberOfMoves + ":" + timeUsed+"\n");
}
bw.close();
System.out.println("Done");
} catch (IOException e) {
e.printStackTrace();
}
}
I have a getHighscore() that reads the two empty " " fields with moves and timeUsed. It is currently able to read this, but i cant write to those empty spaces in the textfile and replace them with actual numbers that i want.
EDIT: With the replace command it just adds it to the bottom of the file.
Is there something wrong with my code that re erases the text that i try to replace or how do i do it?
I tried something like this:
public static void writeToFile(int rows) {
try {
FileWriter fw = new FileWriter(file.getAbsoluteFile(),true);
BufferedWriter bw = new BufferedWriter(fw);
BufferedReader br = new BufferedReader(new FileReader(
"C:\\Users\\Thomas\\Eclipse Workspace\\15Puzzle\\15Puzzle\\src\\FifteenPuzzle\\ScoreBoard.txt"));
if(br.readLine().split(":")[0].equals(Integer.toString(rows+1))){
bw.write(br.readLine().replaceFirst(rows+2+": : ", "yes"));
System.out.println(" lel");
}
bw.close();
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
have you try this ?
String line = br.readLine();
if(line.split(":")[0].equals(Integer.toString(rows+1))){
bw.write(line.replaceFirst(rows+2+": : ", "yes"));
System.out.println(" lel");
}

Sorting a text file in Java

I have a text file with a list of words which I need to sort in alphabetical order using Java. The words are located on seperate lines.
How would I go about this, Read them into an array list and then sort that??
This is a simple four step process, with three of the four steps addressed by Stackoverflow Questions:
Read each line and turn them into Java String
Store each Java String in a Array (don't think you need a reference for this one.)
Sort your Array
Write out each Java String in your array
Here is an example using Collections sort:
public static void sortFile() throws IOException
{
FileReader fileReader = new FileReader("C:\\words.txt");
BufferedReader bufferedReader = new BufferedReader(fileReader);
List<String> lines = new ArrayList<String>();
String line = null;
while ((line = bufferedReader.readLine()) != null) {
lines.add(line);
}
bufferedReader.close();
Collections.sort(lines, Collator.getInstance());
FileWriter writer = new FileWriter("C:\\wordsnew.txt");
for(String str: lines) {
writer.write(str + "\r\n");
}
writer.close();
}
You can also use your own collation like this:
Locale lithuanian = new Locale("lt_LT");
Collator lithuanianCollator = Collator.getInstance(lithuanian);
import java.io.*;
import java.util.*;
public class example
{
TreeSet<String> tree=new TreeSet<String>();
public static void main(String args[])
{
new example().go();
}
public void go()
{
getlist();
System.out.println(tree);
}
void getlist()
{
try
{
File myfile= new File("C:/Users/Rajat/Desktop/me.txt");
BufferedReader reader=new BufferedReader(new FileReader(myfile));
String line=null;
while((line=reader.readLine())!=null){
addnames(line);
}
reader.close();
}
catch(Exception ex)
{
ex.printStackTrace();
}
}
void addnames(String a)
{
tree.add(a);
for(int i=1;i<=a.length();i++)
{
}
}
}
public List<String> readFile(String filePath) throws FileNotFoundException {
List<String> txtLines = new ArrayList<>();
try {
BufferedReader reader = new BufferedReader(new FileReader(filePath));
String line;
while (!((line = reader.readLine()) == null)) {
txtLines.add(line);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return txtLines.stream().sorted().collect(Collectors.toList());
}

Categories

Resources