Creating folder from text - java

I am getting
newDir D:\template_export\template\attachments\processed\enumeration\blocker.gif\enumeration\critical.gif\enumeration\high.gif\enumeration\low.gif\enumeration\major.gif\enumeration\medium.gif\enumeration\minor.gif\enumeration\normal.gif\enumeration\unassigned.gif\enumeration\unassigned2.gif\workflow\close.gif\workflow\defer.gif\workflow\duplicate.gif\workflow\inprogress.gif\workflow\new.gif\workflow\open.gif\workflow\reject.gif\workflow\remind.gif\workflow\reopen.gif\workflow\resolve.gif\workflow\unconfigure.gif\workflow\unresolve.gif\workflow\verify.gif\workflow\wontdo.gif\workflow\works.gif\workitemtype\bug.gif\workitemtype\enhancement.gif\workitemtype\general.gif\workitemtype\task.gif\workitemtype
new directory false
reached
java.nio.file.NoSuchFileException: D:\template_export\template\attachments\1.gif -> D:\template_export\template\attachments\processed\enumeration\blocker.gif\enumeration\critical.gif\enumeration\high.gif\enumeration\low.gif\enumeration\major.gif\enumeration\medium.gif\enumeration\minor.gif\enumeration\normal.gif\enumeration\unassigned.gif\enumeration\unassigned2.gif\workflow\close.gif\workflow\defer.gif\workflow\duplicate.gif\workflow\inprogress.gif\workflow\new.gif\workflow\open.gif\workflow\reject.gif\workflow\remind.gif\workflow\reopen.gif\workflow\resolve.gif\workflow\unconfigure.gif\workflow\unresolve.gif\workflow\verify.gif\workflow\wontdo.gif\workflow\works.gif\workitemtype\bug.gif\workitemtype\enhancement.gif\workitemtype\general.gif\workitemtype\task.gif\workitemtype\unknown.gifprocess_template_license.htmltemplate.messagestemplate_en_US.messages
at sun.nio.fs.WindowsException.translateToIOException(Unknown Source)
at sun.nio.fs.WindowsException.rethrowAsIOException(Unknown Source)
at sun.nio.fs.WindowsFileCopy.move(Unknown Source)
at sun.nio.fs.WindowsFileSystemProvider.move(Unknown Source)
at java.nio.file.Files.move(Unknown Source)
at Test.main(Test.java:60)
Error.
My code is :
public class Test {
public static void main(String[] args) {
File orgDirectory = new File("D://template_export/template/attachments"); // replace this filename
// with the path to the folder
// that contains the original images
String fileContent = "";
try (BufferedReader br = new BufferedReader(new FileReader(new File(orgDirectory, "attachments.txt")))) {
for (String line;
(line = br.readLine()) != null;) {
fileContent += line;
}
} catch (Exception e) {
e.printStackTrace();
}
String[] newLocations = fileContent.split(",");
File[] orgFiles = orgDirectory.listFiles(new FileFilter() {#Override
public boolean accept(File pathname) {
return pathname.getPath().endsWith(".gif");
}
});
File destinationFolder = new File("D://template_export/template/attachments/processed");
if (!destinationFolder.exists()) {
System.out.println("here" + destinationFolder.mkdir());
}
int max = Math.min(orgFiles.length, newLocations.length);
for (int i = 0; i < max; i++) {
String newLocation = newLocations[i];
int lastIndex = newLocation.lastIndexOf("/");
if (lastIndex == -1) {
continue;
}
String newDirName = newLocation.substring(0, lastIndex);
System.out.println("newDirName " + newDirName);
String newName = newLocation.substring(lastIndex);
System.out.println("newName " + newName);
File newDir = new File(destinationFolder, newDirName);
System.out.println("newDir " + newDir);
if (!newDir.exists()) {
System.out.println("new directory " + newDir.mkdir());
}
try {
System.out.println("reached");
Files.move(orgFiles[i].toPath(), new File(newDir, newName).toPath(), StandardCopyOption.REPLACE_EXISTING);
} catch (IOException e) {
e.printStackTrace();
}
}
}

You're concatenating all the lines of the attachments.txt file into a single destination string. Judging from the exception message, it appears that the attachments file does not contain commas at the end of each line. Thus you end up with a destination consisting of a single file name, seemingly in a deeply nested directory.
Instead, I suggest that you read the lines in one at a time into an ArrayList<String>, rather than concatenating and later splitting the destinations.
ArrayList<String> newLocations = new ArrayList<>();
try (BufferedReader br = new BufferedReader(new FileReader(new File(orgDirectory, "attachments.txt")))) {
for (String line; (line = br.readLine()) != null;) {
newLocations.add(line);
}
} catch (Exception e) {
e.printStackTrace();
}
Then you can use newLocations.size() where you now use newLocations.length and use newLocations.get(i) where you use newLocations[i].
EDIT: As #griFlo points out in a comment, a simpler alternative to reading the file into a list of lines is:
List<String> newLocations = Files.readAllLines(Paths.get("attachments.txt"));
If the file will not read properly with UTF-8 decoding (which is what the above call will use), or if you're compiling with Java 7, you'll have to use the two-argument version of readAllLines():
List<String> newLocations = Files.readAllLines(Paths.get("attachments.txt"),
StandardCharsets.US_ASCII); // or whatever encoding is appropriate

Related

Array returning null

I'm trying to read into a csv file and placing the line into an array. But when I print the array out it is null.
Here is the code:
public static String[] readFile(String inFilename)
{
int lineTotal = getLineNum(inFilename);
if (lineTotal == 0)
{
System.out.println("The file is empty ");
}
FileInputStream fileStrm = null;
InputStreamReader rdr;
BufferedReader bufRdr;
String[] resultArrayOne = new String[lineTotal + 1];
String line;
try
{
fileStrm = new FileInputStream(inFilename); //open file
rdr = new InputStreamReader(fileStrm); //create a reader to read the stream
bufRdr = new BufferedReader(rdr);//read file line by line
int lineNum;
String[] resultArray = new String[lineTotal];
String info;
lineNum = 0;
while ((line = bufRdr.readLine()) != null) //While not end-of-file, process and read lines
{
info = line;
System.out.println(info);
resultArray[lineNum] = info;
lineNum++;
}
fileStrm.close(); //Clean up the stream
resultArrayOne = resultArray;
}
catch (IOException e) // MUST catch IOExceptions
{
if (fileStrm != null) //Clean up the stream if it was opened
{
try
{
fileStrm.close();
}
catch (IOException ex2) { } // We can’t do anything more!
}
System.out.println("Error in file processing: " + e.getMessage()); //Or do a throw
}
return resultArrayOne;
}
When printing out the line before placing it into the array the return is fine, but when placed into the array it become null.
edit:
Here is the full FileIO code:
public static String[] Import()
{
Scanner sc = new Scanner(System.in);
System.out.println("Please enter the File Name: ");
String fileName = sc.nextLine();
int length = getLineNum(fileName);
String[] array = new String[length+1];
array = readFile(fileName);
return array; //array is just strings
}
public static int getLineNum(String inFilename)
{
FileInputStream fileStrm = null;
InputStreamReader rdr;
BufferedReader bufRdr;
String line;
int lineNum = 0;
try
{
fileStrm = new FileInputStream(inFilename); //open file
rdr = new InputStreamReader(fileStrm); //create a reader to read the stream
bufRdr = new BufferedReader(rdr);//read file line by line
lineNum = 0;
while ((line = bufRdr.readLine()) != null) //While not end-of-file, process and read lines
{
lineNum++;
}
fileStrm.close(); //Clean up the stream
}
catch (IOException e) // MUST catch IOExceptions
{
if (fileStrm != null) //Clean up the stream if it was opened
{
try
{
fileStrm.close();
}
catch (IOException ex2) { } // We can’t do anything more!
}
System.out.println("Error in file processing: " + e.getMessage()); //Or do a throw
}
return lineNum;
}
I'm not too sure how to insert a sample file but it is something like this:
SHOP1, STORE2, 45
SHOP2, SHOP1, 67
STORE6, SHOP1, 90
...
edit 2:
I added the code that uses this
String[] locationArrayOne = new String[1000];
locationArrayOne = FileIO.Import();
for (int yyy = 0; yyy < locationArrayOne.length; yyy++)
{
System.out.print(locationArray[yyy]);
}
Your code looks fine but here is how I would debug the problem:
Before lineNum++, I will print the value of resultArray[lineNum] instead of info to see if the program was able to retrieve the line and store it to the array.
Remove the initialization of String[] resultArrayOne and after fileStrm.close(), use resultArrayOne = resultArray.clone() to copy the values of resultArray to resultArrayOne. Copying an array by assignment (array1 = array2) could have side-effects you do not want in your program since you are making both arrays refer to the same object. Check this related question here
Also, why not use resultArrayOne directly when storing the lines?

Replace the first line with the longest java text file

i need to replace the first line in the text file with the longest and vice versa. Please tell me what i need to fix and add. At this stage the program looks for the longest line properly. I'm new to Java, I'm sure there is not much to fix, but I do not know what exactly is needed. Also, if possible, help implement the output of the result in a new file.
The code still looks like this:
package pkg;
import java.io.*;
import java.nio.file.Files;
import java.util.*;
public class Main {
static int previousLongLine = 0;
public void printLongLine(HashMap longLineMap) {
Set keyofSet = longLineMap.keySet();
Iterator itr = keyofSet.iterator();
while (itr.hasNext()) {
Integer keys = (Integer) itr.next();
String value = (String) longLineMap.get(keys);
System.out.println("Line Number of Longest line: " + keys
+ "\nLongest line: " + value);
}
}
public static void main(String []args){
// TODO Auto-generated method stub
String fileName = "G:\\colege\\bursa\\Colege\\Programing\\pkg\\File1.txt";
// This will reference one line at a time
String line = null;
int key = 0;
int lineSize = 0, lineNumber = 0;
Main ln = new Main();
HashMap longLineMap = new HashMap();
try {
// FileReader reads text files in the default encoding.
FileReader fileReader = new FileReader(fileName);
// Always wrap FileReader in BufferedReader.
BufferedReader bufferedReader = new BufferedReader(fileReader);
while ((line = bufferedReader.readLine()) != null) {
lineNumber++;
lineSize = line.length();
if (lineSize > previousLongLine) {
previousLongLine = lineSize;
longLineMap.clear();
longLineMap.put(lineNumber, line);
}
if(lineNumber == 1){
String old = line;
String newl = old.replaceFirst(old, String.valueOf(previousLongLine));
}
}
//close files.
bufferedReader.close();
} catch (FileNotFoundException ex) {
System.out.println("Unable to open file '" + fileName + "'");
} catch (IOException ex) {
System.out.println("Error reading file '" + fileName + "'");
}
ln.printLongLine(longLineMap);
}
}
You can achieve this with a simple stream operation.
Info on stream: https://docs.oracle.com/javase/8/docs/api/java/util/stream/Stream.html
I've used try-with-resource, which auto-closes the resource after processing has ceased.
Info on try-with-resource: https://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html
Read file into an ArrayList
Create another List to hold the sorted elements.
Open a stream on the ArrayList which holds the input data.
Sort the lines into size order. Use Comparator.reverseOrder() for largest to smallest
Using a downstream collector store the output as a new list.
Write sorted list to file.
Reading file:
String inputFile = "files/longestLine.txt";
List<String> lines = new ArrayList<>();
try(BufferedReader bufferedReader = new BufferedReader(new FileReader(inputFile))) {
String line = bufferedReader.readLine();
while(line != null){
lines.add(line);
line = bufferedReader.readLine();
}
} catch (IOException e) {
e.printStackTrace();
}
Use a stream to sort the lines into size order.
List<String> sortedLines = lines.stream()
.sorted(Comparator.reverseOrder())
.collect(Collectors.toList());
Write to file:
String outputFile = "outputFile.txt";
try(BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(outputFile))) {
for (String line: sortedLines) {
bufferedWriter.write(line);
bufferedWriter.newLine();
}
} catch (IOException e) {
e.printStackTrace();
}

How to make characters in Eclipse txt file visible?

I have a txt file "HighScoreList.txt" in my project.
The Problem is that there must be characters on that file, but when I open it in Eclipse, its empty. Removing it from eclipse and opening it with notepad removes all characters from that file.
My method writes on that file.
public void registerHighScore(Player p) {
int score = p.getScore();
String name = p.getName();
{
currentHighScores.add("X. "+name+" - "+score); //place doesnt matter as the actual place gets determined in formatHList
formatHList();
}
try {
BufferedWriter writer = new BufferedWriter(
new FileWriter(HighScoreManager.class.getResource("/highscore/HighScoreList.txt").getPath()));//persistancy
for (String s : currentHighScores) {
writer.write(s);
writer.newLine();
writer.flush();
}
writer.close();
} catch (IOException e) {
return;
}
}
I have checked that there must be characters in the textfile because
public ArrayList<String> getCurrentHighScores() {
ArrayList<String> result = new ArrayList<String>();
try {
BufferedReader bufferedReader = new BufferedReader(
new FileReader(HighScoreManager.class.getResource("/highscore/HighScoreList.txt").getPath()));
String line;
while ((line = bufferedReader.readLine()) != null) {
result.add(line);
}
bufferedReader.close();
return result;
} catch (IOException e) {
}
return null;
}
The ArrayList createt with that method actually contains Strings in the X. Name - Score format.

Replace multiple string in a file java

I am trying to replace multiple strings in a file from source as ArrayList. But the application is erasing the old string before replacing a new one. Please help.
public static void writeNewFile(File template, ArrayList<String> data) {
File file = template;
String nameToReplace = "((name))";
String productToReplace = "((product))";
String giftToReplace = "((gift))";
String giftValueToReplace = "((gift-value))";
String outputFileName = data.get(0);
String workingDirectory = System.getProperty("user.dir");
Scanner scanner = null;
try {
scanner = new Scanner(file);
PrintWriter writer = new PrintWriter(workingDirectory + "\\Output\\" + outputFileName);
while (scanner.hasNextLine()) {
String line1 = scanner.nextLine();
writer.println(line1.replace(nameToReplace, data.get(1)));
writer.println(line1.replace(productToReplace, data.get(2)));
}
} catch (Exception e) {
System.out.println("Destination folder not found");
}
}
This worked for me
try {
BufferedReader reader = new BufferedReader(new FileReader(file));
String line = "", oldtext = "";
while ((line = reader.readLine()) != null) {
oldtext += line + "\r\n";
}
reader.close();
String result = oldtext.replace(nameToReplace, data.get(1))
.replace(productToReplace, data.get(2))
.replace(giftToReplace, data.get(3));
// Write updated record to a file
FileWriter writer = new FileWriter(workingDirectory + "\\Output\\" + outputFileName);
writer.write(result);
writer.close();
} catch (IOException ioe) {
System.out.println("Write error");
}

How to extract starting of a String in Java

I have a text file with more than 20,000 lines and i need to extract specific line from it. The output of this program is completely blank file.
There are 20,000 lines in the txt file and this ISDN line keeps on repeating lots of time each with different value. My text file contains following data.
RecordType=0(MOC)
sequenceNumber=456456456
callingIMSI=73454353911
callingIMEI=85346344
callingNumber
AddInd=H45345'1
NumPlan=H34634'2
ISDN=94634564366 // Need to extract this "ISDN" line only
public String readTextFile(String fileName) {
String returnValue = "";
FileReader file = null;
String line = "";
String line2 = "";
try {
file = new FileReader(fileName);
BufferedReader reader = new BufferedReader(file);
while ((line = reader.readLine()) != null) {
// extract logic starts here
if (line.startsWith("ISDN") == true) {
System.out.println("hello");
returnValue += line + "\n";
}
}
} catch (FileNotFoundException e) {
throw new RuntimeException("File not found");
} finally {
if (file != null) {
try {
file.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return returnValue;
}
We will assume that you use Java 7, since this is 2014.
Here is a method which will return a List<String> where each element is an ISDN:
private static final Pattern ISDN = Pattern.compile("ISDN=(.*)");
// ...
public List<String> getISDNsFromFile(final String fileName)
throws IOException
{
final Path path = Paths.get(fileName);
final List<String> ret = new ArrayList<>();
Matcher m;
String line;
try (
final BufferedReader reader
= Files.newBufferedReader(path, StandardCharsets.UTF_8);
) {
while ((line = reader.readLine()) != null) {
m = ISDN.matcher(line);
if (m.matches())
ret.add(m.group(1));
}
}
return ret;
}

Categories

Resources