So I have this code where it prompts the user to type in a file name for the input file and the file name for the output file. I have a string called 'names' which will then be stored into the input file that was created by the user. I've got this part down.
import com.sun.org.apache.xpath.internal.SourceTree;
import java.io.*;
import java.util.Scanner;
public class Main {
public static void main(String[] args) throws IOException {
FileWriter writer = new FileWriter(chooseFile("input"));
FileWriter writer2 = new FileWriter(chooseFile("output"));
String separator = String.format("%n");
for(String name: names){
writer.write(name);
writer.write(separator);
}
}
}
public static File chooseFile(String type) {
String fname = null;
}
return file;
}
}
Something like so should modify your names list to all caps.
for (int i = 0; i < names.length; i++) {
names[i] = names[i].toUpperCase();
// writer2.write(names[i]);
}
Related
I have text files.
album.txt
new_album.txt
Each text files contains some folder name.
For example,
album.txt contains
#Event1
#Event2
#Event3
and new_album.txt contains
#Event1(update20-05-2015)
#Event2(update03-03-2016)
#Event3(update15-08-2016)
#Event4(update30-07-2017)
I want to compare similar folder name from album.txt with new_album.txt line by line, then put folder name that similar from album.txt to similar.txt and put folder name that not match to not_match.txt .
Output in similar.txt
#Event1
#Event2
#Event3
Output in not_match.txt
#Event4(update30-07-2017)
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
public class CompareFileName {
public static void main(String[] args) throws Exception {
BufferedReader br1 = null;
BufferedReader br2 = null;
String sCurrentLine;
List<String> list1 = new ArrayList<String>();
List<String> list2 = new ArrayList<String>();
br1 = new BufferedReader(new FileReader("album.txt"));
br2 = new BufferedReader(new FileReader("new_album.txt"));
while ((sCurrentLine = br1.readLine()) != null) {
list1.add(sCurrentLine);
}
while ((sCurrentLine = br2.readLine()) != null) {
list2.add(sCurrentLine);
}
//This part is my problem
List <String> list_similar = new ArrayList<String>();
List <String> list_not_match = new ArrayList<String>();
for (String string : list1) {
if(string.matches("list2")){ //I don't know how to compare similar folder name from list2 with list1.
list_similar.add(string);
}else{list_not_match.add(string)}
}
//This part is the part I use for add string to text file but it not complete I want to write string from list_similar to similar.text and list_not_match to not_match.txt
file = new File("similar.txt");
fileName = "similar.txt";
str = file.list();
try{
PrintWriter outputStream = new PrintWriter(fileName);
for(String string:str){
outputStream.println(string);
}
outputStream.close();
System.out.println("get name complete");
}
catch (FileNotFoundException e){
e.printStackTrace();
}
System.out.println("done.");
}
If you want to read something from files, you can use these streams.
public static void main(String[] args) throws IOException {
BufferedReader reader = new BufferedReader(new FileReader(new File("path\\to\\your\\file.txt"))); //or any format
BufferedWriter writer = new BufferedWriter(new FileWriter(new File("path\\to\\your\\second\\file.txt")));
//read one line from your file
String line = reader.readLine();
//write something to your file
writer.write(line);
}
If you want to read folder names you can use this.
File f = f = new File("path\\to\\your\\folder\\with\\files");
File[] files = f.listFiles();
for(File currentFile : files) {
System.out.println(currentFile.getName());
}
If you want to create new files or folders, you can use this.
File f = f = new File("path\\to\\your\\folder\\with\\files");
f.mkdir();
//or
f.mkdirs();
//or if you have File f = new File("myTextFile.txt"); then you can create file using this:
f.createNewFile();
Application (main method)
public class Application {
public static void main(String... aArgs) throws IOException {
InputParser firstListInputParser = new InputParser(new File(/**"Your path to /album.txt"*/));
firstListInputParser.processLineByLine();
List<String> firstList = firstListInputParser.getListWithParsedFolderNames();
firstListInputParser.printMap();
InputParser secondListInputParser = new InputParser(new File(/**"Your path to /new_album.txt"*/));
secondListInputParser.processLineByLine();
List<String> secondList = secondListInputParser.getListWithParsedFolderNames();
secondListInputParser.printMap();
// Create the list with common value and write it to the file
List<String> listWithCommonValues = new ArrayList<String>(firstList);
listWithCommonValues.retainAll(secondList);
Path fileCommon = Paths.get(/**"Your path to /similar.txt"*/);
Files.write(fileCommon, listWithCommonValues, Charset.forName("UTF-8"));
// Create the list with different values and write it to the file
List<String> listWithAllValues = new ArrayList<String>(firstList);
listWithAllValues.addAll(secondList);
//remove the common values from the list with all values
listWithAllValues.removeAll(listWithCommonValues);
Path fileDistincts = Paths.get(/**"Your path to /not_match.txt"*/);
Files.write(fileDistincts, listWithAllValues, Charset.forName("UTF-8"));
}
private static void log(Object aObject){
System.out.println(String.valueOf(aObject));
}
}
Inputparser
/**
* Assumes UTF-8 encoding
*/
public class InputParser {
//create a list to hold the values
List<String> listWithParsedFolderNames = new ArrayList<>();
//private final Path fFilePath;
private final File file;
private final static Charset ENCODING = StandardCharsets.UTF_8;
/**
Constructor.
#param aFileName full name of an existing, readable file.
*/
public InputParser(File aFileName){
//fFilePath = Paths.get(aFileName);
file = aFileName;
}
/**
* Processes each line and calls {#link #processLine(String)}}.
*/
public final void processLineByLine() throws IOException {
try (Scanner fileScanner = new Scanner(file, ENCODING.name())){
while (fileScanner.hasNextLine()){
processLine(fileScanner.nextLine());
}
}
}
/**
Overridable method for processing lines in different ways.
*Parses the line and cuts away the part after '(update'
* Ex1: input line: #Event1(update20-05-2015)
* Ex1: output : #Event1
*
* Ex2: input line: #Event2
* Ex2: output : #Event2
*/
protected void processLine(String aLine){
Scanner scanner = new Scanner(aLine);
if (scanner.hasNext()) {
String name = scanner.next();
String finalName = name.split("\\(update")[0];
//stores the values in the list
listWithParsedFolderNames.add(finalName);
} else {
log("Empty or invalid line. Unable to process.");
}
}
/**
* Prints the content of the listWlistWithParsedFolderNames
*/
public void printMap() {
Iterator it = listWithParsedFolderNames.iterator();
while (it.hasNext()) {
log("The prsed value is: " + it.next());
}
}
/**
* #return the list with values
*/
public List<String > getListWithParsedFolderNames() {
return this.listWithParsedFolderNames;
}
private static void log(Object aObject){
System.out.println(String.valueOf(aObject));
}
}
In the similar.txt it will print:
#Event1
#Event2
#Event3
In the not_match.txt it will print:
#Event4
If you want it to print #Event4(update30-07-2017) into the not_match class you will have to change the list to a key value map that has the parsed input #Event4 as key and the full line #Event4(update30-07-2017) as value. After comparing the keys of the map you can write the values into your file.
I have two text files namely - item.txt (file 1) and temp.txt (file 2). My goal is to search for a name in the file 1 and if found then replace it with a different name and write the updated line to file 2. Also, I have a method that checks for the lines for the string I searched in file 1. The lines that do not contain that string will be added to file 2.
So, here is where I'm stuck. Everything works fine except the part where I want to delete file 1 and rename file 2 by file 1 (i.e item.txt). Can someone please help me with any correction? I am still a beginner in Java, so my code might not be the best looking code as one might expect but this is what I tried so far. Thanks
The problem is when i compile the code the updated data is written to file2 and file1 which was supposed to get deleted doesn't delete. So, what could be the problem?
package project4;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Scanner;
public class kitkat {
PrintWriter out,in;
Scanner in;
Scanner temp;
File file1 = new File("item.txt");
File file2 = new File("temp.txt");
public void write() throws FileNotFoundException {
out = new PrintWriter(file1);
out.println("User1"+ "\t"+"639755"+"\t"+"400");
out.println("User2"+ "\t"+"639725"+"\t"+"800");
out.close();
}
public void nfile() throws IOException {
n = new PrintWriter(new FileWriter(file2,true));
}
Scanner input = new Scanner(System.in);
String replacement = "User3";
String search;
String total;
public void search() {
System.out.println("Enter your search name");
search = input.nextLine();
total = search;
}
public void lolipop() throws IOException {
in = new Scanner(file1);
search();
while(in.hasNext()) {
String a,b,c;
a = in.next();
b = in.next();
c = in.next();
if(a.contains(search)) {
System.out.println("Your match is found"+search);
a = replacement;
System.out.println(a+b+c);
n.file();
n.println(a+"\t"+b+"\t"+c);
n.close();
}
}
}
public void jellybeans() throws IOException {
temp = new Scanner(file1);
while(temp.hasNext()) {
String p,q,r;
p = temp.next();
q = temp.next();
r = temp.next();
if(!(p.contains(total))) {
System.out.println(p+q+r);
n.file();
n.println(p+"\t"+q+"\t"+r);
n.close();
renamefile();
}
}
}
public void renamefile() {
file1.delete();
file2.renameTo(file1);
}
}
package project4;
import java.io.FileNotFoundException;
import java.io.IOException;
public class tuna {
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
kitkat kt = new kitkat();
kt.lolipop();
kt.jellybeans();
}
}
Change this:
public void renamefile() {
String file1Path = file1.getAbsolutePath();
file1.delete();
file2.renameTo(new File(file1Path));
}
According to the Javadoc of File.renameTo(…) the behavior of this method is platform dependent. If the rename does not succeed it simply returns false without throwing an exception. So I guess this would be the case here.
You can try the newer (since Java 7) Files.move(…). This method is platform independent and has propper error handling, throwing exceptions with a problem description.
What I want to do: My class copytest reads a textfile, edits one character and save this new file in a new directory. I want to program a void-method out of it, which does exactly the same and can then be used the following way:
copy(String "C:\\Old.txt", String "C:\\New.txt", int 1, int 1)
Now copy does exactly the same as my old class copytest, it reads the old file, edits it and saves it.
My first idea was to have two files as the first to arguments, but this is obviously impossible. My new idea is to give the method two strings of the wanted directories of the old and the new file. It still doesn't work. I hope, you understand, what I want to do and how to solve this problem.
Old class code (works):
import java.io.*;
import java.util.Scanner;
public class copytest {
public static void main(String[] args) throws Exception {
readFile();
}
public static void readFile() throws Exception {
// Location of file to read
File file = new File("...old.txt");
Scanner scanner = new Scanner(file);
int lineNumber=1;
int charNumber=1;
String wantedChar="r";
int i=0;
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
if (i == lineNumber+2) {
if (line.length() >= charNumber) {
line = line.substring(0,charNumber-1) + wantedChar + line.substring(charNumber);
}
}
writeFile(line);
i++;
}
scanner.close();
System.out.println("File copied.");
}
public static void writeFile(String copyText) throws Exception {
String newLine = System.getProperty("line.separator");
// Location of file to output
Writer output = null;
File file = new File("...new.txt");
output = new BufferedWriter(new FileWriter(file, true));
output.write(copyText);
output.write(newLine);
output.close();
}
}
New void code (first try with file as argument):
public void copy(file old, file new, int x, int y) {
public static void readFile() throws Exception {
Scanner scanner = new Scanner(old);
int lineNumber=y;
int charNumber=x;
String wantedChar="r";
int i=0;
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
if (i == lineNumber+2) {
if (line.length() >= charNumber) {
line = line.substring(0,charNumber-1) + wantedChar + line.substring(charNumber);
}
}
writeFile(line);
i++;
}
scanner.close();
System.out.println("File copied.");
}
public static void writeFile(String copyText) throws Exception {
String newLine = System.getProperty("line.separator");
// Location of file to output
Writer output = null;
File file = new File(new.getPath());
output = new BufferedWriter(new FileWriter(file, true));
output.write(copyText);
output.write(newLine);
output.close();
}
readFile();
}
New try with strings as argument, but still doesn't work:
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.Writer;
import java.util.Scanner;
public class copytestnew {
public void copy(String old, String newone, int x, int y) {
// Location of file to read
File file = new File(old);
Scanner scanner = new Scanner(file);
int lineNumber=y;
int charNumber=x;
String wantedChar="r";
int i=0;
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
if (i == lineNumber+2) {
if (line.length() >= charNumber) {
line = line.substring(0,charNumber-1) + wantedChar + line.substring(charNumber);
}
}
String newLine = System.getProperty("line.separator");
// Location of file to output
Writer output = null;
File file2 = new File(newone);
output = new BufferedWriter(new FileWriter(file2, true));
output.write(line);
output.write(newLine);
output.close();
i++;
}
scanner.close();
System.out.println("File copied");
}
}
I remember you! I answeared you last time on how to replace the char at one of the lines.
First, change the decleration to
public static void copy(String old, String newone, int x, int y) throws IOException {
NOTICE the throws statment!
And now when you want to call this method you should use it inside a try-catch block or declear that you throwing exception same as you did at the copy function.
public void copy(file old, file new, int x, int y) {
public static void readFile() throws Exception {
You're defining a function inside a method. As all functions in java are methods (static or non-static), this is not permitted. Try this:
class IDontKnowHowToNameIt {
public static void copy(file old, file new, int x, int y) {
//...
// call readFile from here
// ...
}
private static void readFile() throws Exception {
//...
}
}
I have two files. One file counts the number of listed events I have in a text file and stores the number of events into the variable "count". I want to then use the value in this variable to do computation in a second file. How do I do this? Do I have to create an object of the class in my first file and then reference it? I need an example please, I cannot seem to get this to work. Here is what I have tried.
My first file:
import java.util.*;
import java.io.*;
public class EventCounter {
public static void main (String [] args) throws IOException{
Scanner file = new Scanner(new File("event.txt"));
int count = 0;
while (file.hasNextLine()) {
count++;
file.nextLine();
}
System.out.println(count); //test
}
}
My Second file:
import java.io.IOException;
import java.io.FileReader;
import java.io.BufferedReader;
public class ReadEventFile {
private String path;
public ReadEventFile(String file) {
path = file;
}
public String[] OpenFile() throws IOException {
FileReader fr = new FileReader(path);
BufferedReader textReader = new BufferedReader(fr);
EventCounter method = new EventCounter(); //make object?
String[] dataTable = new String[count];
int i;
for (i=0; i<count; i++) { //Why count does not exist?
}
My second file does not know that count is a variable from my first file :-(
You seem to have your process flow backwards. The class with the main method will be created and run by the JVM - therefore it's your entry point.
Your ReadEventFile class therefore needs to be told the count when it is created. Simply add it to the constructor:
public static class ReadEventFile {
private final File eventFile;
private final int count;
public ReadEventFile(final int count, final File eventFile) {
this.eventFile = eventFile;
this.count = count;
}
public String[] openFile() throws IOException {
String[] dataTable = new String[count];
int i;
for (i = 0; i < count; i++) {
}
return dataTable;
}
}
Now your EventCounter needs to create a ReadEventFile instance once it knows the count and call the openFile method on it:
public static void main(String[] args) throws IOException {
final File eventFile = new File("event.txt");
int count = 0;
try (Scanner file = new Scanner(eventFile)) {
while (file.hasNextLine()) {
count++;
file.nextLine();
}
}
final ReadEventFile readEventFile = new ReadEventFile(count, eventFile);
final String[] dataTable = readEventFile.openFile();
}
The ReadEventFile does it's work and then returns the String[] back to your EventCounter.
You don't close any of your resources when you are done with them. This is asking for trouble. I have added a Java 7 try-with-resources around your Scanner in the EventCounter.
The design of this program does seem a little odd. There is no logical reason why the EventCounter should be the entry point to the application. I would recommend you create a BootStrap class that holds the main method and is the entry point that then calls both the EventCounter and the ReadEventFile.
Further, the openFile method on the ReadEventFile class isn't well named - it does more than that. Maybe processEventFile or something along those lines would be more appropriate.
your first Program
package farzi;
import java.util.*;
import java.io.*;
public class EventCounter {
public static void main (String [] args) throws IOException
{
EventCounter object = new EventCounter();
System.out.println(object.returnCount());
}
public int returnCount() throws FileNotFoundException
{
Scanner file = new Scanner(new File("event.txt"));
int count = 0;
while (file.hasNextLine()) {
count++;
file.nextLine();
}
System.out.println(count); //test
return count;
}
}
your second program
package farzi;
import java.io.File;
import java.io.IOException;
import java.io.FileReader;
import java.io.BufferedReader;
public class ReadEventFile
{
private String path;
public ReadEventFile(String file)
{
String path = file;
}
public String[] OpenFile() throws IOException {
EventCounter eventCounterObject = new EventCounter();
int countLocal = eventCounterObject.returnCount();
FileReader fr = new FileReader(path);
BufferedReader textReader = new BufferedReader(fr);
EventCounter method = new EventCounter(); //make object?
String[] dataTable = new String[countLocal];
int i;
String[] textData = null;
for (i=0; i<countLocal; i++) { //Why count does not exist?
textData[i] = textReader.readLine();
}
return textData;
}
}
I want to copy the directory structure without copying the content/files. I want to copy only folder structure.
I have written a sample program but it is also copying the content/files also.
import java.io.*;
import java.nio.channels.*;
#SuppressWarnings("unused")
public class CopyDirectory{
public static void main(String[] args) throws IOException{
CopyDirectory cd = new CopyDirectory();
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
String source = "C:\\abcd\\Documents\\1";
File src = new File(source);
String destination = "C:\\abcd\\Documents\\2";
File dst = new File(destination);
cd.copyDirectory(src, dst);
}
public void copyDirectory(File srcPath, File dstPath) throws IOException{
if (srcPath.isDirectory())
{
if (!dstPath.exists())
{
dstPath.mkdir();
}
String files[] = srcPath.list();
for(int i = 0; i < files.length; i++)
{
System.out.println("\n"+files[i]);
copyDirectory(new File(srcPath, files[i]), new File(dstPath, files[i]));
}
}
System.out.println("Directory copied.");
}
}
I am struck at this point.
Thank you.
This worked for me:
import java.io.File;
public class StartCloneFolderOnly {
/**
* #param args
*/
public static void main(String[] args) {
cloneFolder("C:/source",
"C:/target");
}
public static void cloneFolder(String source, String target) {
File targetFile = new File(target);
if (!targetFile.exists()) {
targetFile.mkdir();
}
for (File f : new File(source).listFiles()) {
if (f.isDirectory()) {
String append = "/" + f.getName();
System.out.println("Creating '" + target + append + "': "
+ new File(target + append).mkdir());
cloneFolder(source + append, target + append);
}
}
}
}
So if I'm right, you just want to copy the folders.
1.) Copy directory with sub-directories and files
2.) Place 1. wherever
3a.) Instantiate to list files in parent directory into an arrayList
3b.) Instantiate to list the new subfolders into an arrayList
3c.) Instantiate to list all files in each subfolder into their own arrayLists
4.) Use a for-loop to now delete every file within the new directory and subfolder
From this, you should have a copy of the new directory with all files removed.
import java.io.*;
import java.nio.channels.*;
#SuppressWarnings("unused")
public class CopyDirectory{
public static void main(String[] args) throws IOException{
CopyDirectory cd = new CopyDirectory();
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
String source = "C:\\abcd\\Documents\\1";
File src = new File(source);
String destination = "C:\\abcd\\Documents\\2";
File dst = new File(destination);
cd.copyDirectory(src, dst);
}
public void copyDirectory(File srcPath, File dstPath) throws IOException{
if (srcPath.isDirectory())
{
if (!dstPath.exists())
{
dstPath.mkdir();
}
String files[] = srcPath.list();
for(int i = 0; i < files.length; i++)
{
System.out.println("\n"+files[i]);
copyDirectory(new File(srcPath, files[i]), new File(dstPath, files[i]));
}
}
System.out.println("Directory copied.");
}
}