Generating custom text files in java - java

public class ScriptCreator {
public static void main(String[] args) throws IOException {
#Choose the CSV file that I am importing the data from
String fName = "C:\\Users\\MyUser\\Downloads\\CurrentApplications (1).csv";
String thisLine;
int count = 0;
FileInputStream fis = new FileInputStream(fName);
DataInputStream myInput = new DataInputStream(fis);
int i = 0;
#Prints the List of names in the CSV file
while((thisLine = myInput.readLine()) != null){
String strar[] = thisLine.split(",");
Printer(strar[0]);
}
}
public static void Printer(String arg) throws IOException{
#Want to pull from the String strar[0] from above
#Says that it cannot be resolved to a variable
String name = arg;
String direc = "C:/Users/MyUser/Documents/";
String path = "C:/Users/MyUser/Documents";
Iterable<String> lines = Arrays.asList("LOGIN -acceptssl ServerName","N " + name + " " + direc ,"cd " + name,"import " + path + "*.ppf" + " true","scan", "publishassessase -aseapplication " + name,"removeassess *","del " + name );
Path file = Paths.get(name + ".txt");
Files.write(file, lines, Charset.forName("UTF-8"));
}
}
Hello everyone and thank you in advance for any help that you may be able to give me. I am trying to create a java program that will pull names from a CSV file and take those names to generate custom outputs for text files. I am having a hard time being able to set a variable that I can use to grab the names that are being printed and using them to generate a text file by setting the name variable.
I am also going to need some help in making sure that it creates the amount of scripts for the amount of names in the CSV file. Ex. 7 names in CSV makes 7 custom .txt files, each with its appropriate name.
Any help is greatly appreciated!
Edit: I have updated my code to match the correction that was needed to make the code work.

It looks like you have some scoping issues. Whenever you declare a variable, it only exists within the boundaries of its closest set of braces. By declaring strar in your main method, the only place you can explicitly use it is within your main method. Your Printer() method doesn't have any previous mention of strar, and the only way it can know about it is by passing it as an argument to the function.
i.e.
Printer(String[] args)
Or, better yet:
Printer(String arg)
and then call it in your while loop with
Printer(strar[0]);
Also, your Printer method begins with a "for each" loop called on strar[0], which is not a valid target for a foreach loop anyway, because if I recall correctly, String isn't an Iterable object. If you implemented the Printer function in the way I recommended, you won't need a for each loop anyway, as there will only be one name passed at a time.

Related

How can I print 2 arrays with different values in java?

I am trying to print 2 different arrays, One array has the name of the file and the other array has the content of the csv file.
First I am reading the contents of the given file through the path and then putting the content of the .csv file into an array which is nextLine[]
public static void fileRead(File file) throws IOException, CsvException {
CSVReader csvReader = new CSVReaderBuilder(new FileReader(file)).withSkipLines(1).build();
String[] nextLine;
File folder = new File("src/main/resources/FolderDocumentsToRead");
String[] fileList = folder.list();
while((nextLine = csvReader.readNext())!=null){
System.out.println("Name of file: "+fileList[0]+", Title of Text: "+nextLine[0]);
}
}
}
The output I am trying to get is meant to look like;
Name of file: ATale.csv, Title of Text: A TALE OF THE RAGGED MOUNTAINS
Name of file: Diggling.csv, Title of Text: DIDDLING
The output I am getting looks like;
Name of file: ATale.csv, Title of Text: A TALE OF THE RAGGED MOUNTAINS
Name of file: ATale.csv, Title of Text: DIDDLING
I have tried using loops to get to the correct solution but I was just getting errors thrown at me and having a hard time with them.
I'm fairly new to using arrays and java in general, any tips would be appreciated even a tip towards getting the solution.
P.S first time using Stack overflow ahaha
Before the while loop, if you create a variable to keep track of the selected index then you will be able to modify it and have the change stay after the loop has finished.
int index = 0;
while(csvReader.hasNext())
{
String fileName = fileList[index];
String title = nextLine[index];
index++;
...
}
The line
while((nextLine = csvReader.readNext())!=null)
can be/should be rewritten like so:
while(csvReader.hasNext())
{
nextLine = csvReader.readNext();
...
}
This helps a lot with reading/debugging
NOTE this is not any sort of solution but a recommendation for ease-of-use

Implementing language locales into array to be used in a loop

I'm trying to read every file in a directory, clean up with java util.locale, then write to a new directory. The reading and writing methods work, the Locale.SPANISH might be the issue as I have read in other posts.
I iterated through the available languages in the java.util.locale, spanish was in there.
First, the array issue: the following extract of code below is the long way of entering the Locale.(LANGUAGE) into the array. This seems to work fine. However, I can't understand why the 'short' way doesn't seem to work.
String[] languageLocale = new String[fileArray.length];
languageLocale[0] = "Locale.ENGLISH";
languageLocale[1] = "Locale.FRENCH";
languageLocale[2] = "Locale.GERMAN";
languageLocale[3] = "Locale.ITALIAN";
languageLocale[4] = "Locale.SPANISH";
The short way:
String[] languageLocale = new String[("Locale.ENGLISH" , "Locale.FRENCH" , "Locale.GERMAN" , "Locale.ITALIAN" , "Locale.SPANISH")];
I need to input the Locale.(langauge) into a string so they can be called in the following:
File file = new File("\\LanguageGuessing5.0\\Learning\\");
File[] fileArray = file.listFiles();
ArrayList<String> words = new ArrayList<String>();
for (int i = 0; i < fileArray.length; i++) {
if (fileArray[i].isFile()) {
if (fileArray[i].isHidden()) {
continue;
} else {
String content = readUTF8File("\\LanguageGuessing5.0\\Learning\\"+fileArray[i].getName());
words = extractWords(content, languageLocale[i]);
outputWordsToUTF8File("\\LanguageGuessing5.0\\Model\\"+ fileArray[i].getName() + "out.txt", words);
}
} else if (fileArray[i].isDirectory()) {
System.out.println("Directory " + fileArray[i].getName());
}
}
The following method call:
words = extractWords(content, languageLocale[i]);
also presents the following error:
The method extractWords(String, Locale) in the type CleaningText(the class name) is not applicable for the arguments (String, String)
My understanding is that while the array argument is not a locale, the string holds the correct text to make it valid. I'm clearly incorrect, I'm hoping someone could explain how this works.
The input types of the methods are below for context:
public static String readUTF8File(String filePath)
public static ArrayList extractWords(String inputText, Locale currentLocale)
public static void outputWordsToUTF8File(String filePath, ArrayList wordList)
Many thanks in advance

Convert .prn file to csv file format in java

need your help to convert prn file to csv file using java.
Thank you so much.
Below is my prn file.
i would like to make it shows like this
Thank you so much.
In your example you have four entries as input, each in a row. In your result table they all are in one row. I assume the input describes a complete prn set. So if a file would contain n prn sets, it would have n * 4 rows.
To map the pm set to a csv file you have to
read in the entries from the input file
write a header row (with eight titles)
extract in each entry the relevant values
combine the extracted values from four entries in sequence to one csv row
write the row
repeat steps 3 to 5 as long as there are further entries
Here is my suggestion:
public class PrnToCsv {
private static final String DILIM_PRN = " ";
private static final String DILIM_CSV = ",";
private static final Pattern PRN_SPLITTER = Pattern.compile(DILIM_PRN);
public static void main(String[] args) throws URISyntaxException, IOException {
List<String> inputLines = Files.readAllLines(new File("C://Temp//csv/input.prn").toPath());
List<String[]> inputValuesInLines = inputLines.stream().map(l -> PRN_SPLITTER.split(l)).collect(Collectors.toList());
try (BufferedWriter bw = Files.newBufferedWriter(new File("C://Temp//csv//output.csv").toPath())) {
// header
bw.append("POL1").append(DILIM_CSV).append("POL1_Time").append(DILIM_CSV).append("OLV1").append(DILIM_CSV).append("OLV1_Time").append(DILIM_CSV);
bw.append("POL2").append(DILIM_CSV).append("POL2_Time").append(DILIM_CSV).append("OLV2").append(DILIM_CSV).append("OLV2_Time");
bw.newLine();
// data
for (int i = 0; i + 3 < inputValuesInLines.size(); i = i + 4) {
String[] firstValues = inputValuesInLines.get(i);
bw.append(getId(firstValues)).append(DILIM_CSV).append(getDateTime(firstValues)).append(DILIM_CSV);
String[] secondValues = inputValuesInLines.get(i + 1);
bw.append(getId(secondValues)).append(DILIM_CSV).append(getDateTime(secondValues)).append(DILIM_CSV);
String[] thirdValues = inputValuesInLines.get(i + 2);
bw.append(getId(thirdValues)).append(DILIM_CSV).append(getDateTime(thirdValues)).append(DILIM_CSV);
String[] fourthValues = inputValuesInLines.get(i + 3);
bw.append(getId(fourthValues)).append(DILIM_CSV).append(getDateTime(fourthValues));
bw.newLine();
}
}
}
public static String getId(String[] values) {
return values[1];
}
public static String getDateTime(String[] values) {
return values[2] + " " + values[3];
}
}
Some remarks to the code:
Using the nio-API you can read the whole file with one line of code.
To extract the values of an entry line I used a Pattern to split the line into an array with each single word as a value.
Then it is easy get the relevant values of an entry using the appropriate array indexes.
To write the csv file line by line (without additional libs) you can use a BufferedWriter.
The file you're writting to is a resource. It is recommended to use resources with the try-with-resource-statement.
I hope I could answer your question.

Giving another class variablevalues before the variables are declared in Java

I am trying to pass values to variables that probably are not declared yet.
From my main source class I am giving another's class some values, but later on it seems like the values are gone.
Source code:
server.java (main):
public class server {
public static void main(String[] args) {
//Print a simple message to the user to notify there is something going on...
System.out.println("Starting server, please wait...");
//Connecting all class files to the server.
filehandler filehandlerclass = new filehandler();
networking networkingclass = new networking();
//End of class files connecting.
//Preparing the filehandler's file information to open a new filestream.
filehandlerclass.filetohandlename = "server";
filehandlerclass.filetohandleextention = "ini";
filehandlerclass.filetohandlepath = "configs\\";
//Request a new filestream using the filehandler's file variables.
filehandlerclass.openfilestream(filehandlerclass.filestream, filehandlerclass.filetohandle);
//Checks if the filehandler has tried to open a filestream.
if(filehandlerclass.filestreamopen == true) {
//Request a check if the filestream was opened sucessfully.
filehandlerclass.filestreamexists(filehandlerclass.filestream);
}
//If the filehandler has not tried to open a filestream...
else {
System.out.println("Error: The filehandler does not seem to have tried to open a filoestream yet.");
System.out.println("A possibility is that the server could not call the method from the filehandler properly.");
}
//Checks if the boolean "filestreamexists" from the filehandlerclass is true.
if(filehandlerclass.filestreamexists(filehandlerclass.filestream) == true) {
//The filestream seems to exist, let's read the file and extract it's information.
filehandlerclass.readfile(filehandlerclass.filestream);
}
else {
filehandlerclass.openfilestream(filehandlerclass.filestream, filehandlerclass.filetohandle);
}
}
}
filehandler.java:
//Imports the java.io library so the filehandler can read and write to text files.
import java.io.*;
public class filehandler {
//Variables for the filehandler class.
public String filetohandlename;
public String filetohandleextention;
public String filetohandlefullname = filetohandlename + "." + filetohandleextention;
public String filetohandlepath;
public String filetohandle = filetohandlepath + filetohandlefullname;
//Boolean that is true if the filehandler's "openfilestream"-method has tried to open a filestream.
//Is false as long as none filestreams have been touched.
public boolean filestreamopen = false;
//Declares a variable for the filestream to access text files.
public File filestream;
//End of variable list.
//Called to open a filestream so the server can load properties from text files.
public void openfilestream(File filestream, String filetohandle) {
//Tell the user that a filestream is about to be opened.
System.out.println("Opening filestream for \"" + filetohandlefullname + "\"...");
//Open a filestream called "filestream" using the variable "filetohandle"'s value
//as information about wich file to open the filestream for.
filestream = new File(filetohandle);
//Turn the boolean "filestreamopen" to true so next time the server checks it's
//value, it knows if the filehandler has tried to open a filestream.
filestreamopen = true;
}
//Boolean that checks if the filestream exists.
public boolean filestreamexists(File filestream) {
//Tell the user that a check on the filestream is going on.
System.out.println("Checking if filestream for \"" + filetohandlefullname + "\" exists...");
//If the filestream exists...
if(filestream.exists()) {
//Tell the user that the filestream exists.
System.out.println("Filestream for \"" + filetohandlefullname + "\" exists!");
//Make the boolean's value positive.
return true;
}
//If the filestream does not exist...
else {
//Tell the user that the filestream does not exist.
System.out.println("Filestream for \"" + filetohandlefullname + "\" does not exist!");
//Make the boolean's value negative.
return false;
}
}
//Called to read files and collect it's information.
public void readfile(File filestream) {
//Checks if the file that is going to be read is a configuration file.
if(filetohandleextention == "ini") {
//Tell the user that a configuration file is going to be read.
System.out.println("Extracting information from the configuration file \"" + filetohandle + "\".");
}
}
}
networking.java:
public class networking {
}
Problem:
server.java is going to serve commands to the source files and tell them what to do.
The source files are not going to act on their own unless server.java has given them a command.
This way I am planning to be able to write simple function calls in server.java to do greater tasks from the different source files.
server.java seems to pass the variables "filetohandlename", "filetohandleextention" and "filetohandlepath" before the variables are declared and when they get declared, they are declared with "null" as value.
Result:
I get no errors when I compile it.
All I think is happening is a miss match with giving the variables that specifies the file that is going to be read's proper values.
It also throws an exception which I have not been careing to look into for now, either it's because "null.null" does not exist or that I wrote the code wrong.
Final request:
Does anybody know if I can make a method for recieving the variables values
or if there is another more proper way around?
Could I probably make an array of the variables in server.java and collect the values from that array?
Thank you so much for your time.
This:
public String filetohandlename;
public String filetohandleextention;
public String filetohandlefullname = filetohandlename + "." + filetohandleextention;
initialises the first two variables to null, and the third to "null.null". Note that if you change one of the component variables that have made up filetohandlefullname, it won't then change the value of filetohandlefullname. If you want that to happen, then filetohandlefullname should be replaced by a method performing the appending operation.
This:
public void openfilestream(File filestream, String filetohandle)
passes a different variable filetohandle into the method. That variable is distinct from this.filetohandle.
I think there's a numberof issues with this code (above) and I'd do the following.
replace variables instantiated via other variables with methods that perform this dynamically. That way, when you change var1 that you'd expect to change the value of var2, that will happen automatically via a method return. e.g create a private method getFileToHandleFullName() and bin the corresponding variable
scope class members with this
where possible, make those members final so you don't inadvertently change them
This line
public String filetohandlefullname = filetohandlename + "." + filetohandleextention;
is executed when you instantiate the class (ie filehandler filehandlerclass = new filehandler();). At that point in time both variables are unset, thus filetohandlefullname is initialized to null.null
But there's a number of other problems with your code as well, like
//Request a new filestream using the filehandler's file variables.
filehandlerclass.openfilestream(filehandlerclass. filestream,filehandlerclass.filetohandle);
eg you're passing parameters that are fields from the same instance. That's totally useless as the method already has access to those, and it's very confusing.
And maybe slightly controversial:
//Make the boolean's value positive.
return true;
Comments are only useful if they clarify code that without them would be less obvious, and they have to be 100% true and not, as happens so often, what the program wishes the code would do. In this specific case neither of these conditions is fulfilled as the comment doesn't clarify what's going on, and actually the method's return value is set, not some nondescript "boolean's value"

Java: splitting the filename into a base and extension

Is there a better way to get file basename and extension than something like
File f = ...
String name = f.getName();
int dot = name.lastIndexOf('.');
String base = (dot == -1) ? name : name.substring(0, dot);
String extension = (dot == -1) ? "" : name.substring(dot+1);
I know others have mentioned String.split, but here is a variant that only yields two tokens (the base and the extension):
String[] tokens = fileName.split("\\.(?=[^\\.]+$)");
For example:
"test.cool.awesome.txt".split("\\.(?=[^\\.]+$)");
Yields:
["test.cool.awesome", "txt"]
The regular expression tells Java to split on any period that is followed by any number of non-periods, followed by the end of input. There is only one period that matches this definition (namely, the last period).
Technically Regexically speaking, this technique is called zero-width positive lookahead.
BTW, if you want to split a path and get the full filename including but not limited to the dot extension, using a path with forward slashes,
String[] tokens = dir.split(".+?/(?=[^/]+$)");
For example:
String dir = "/foo/bar/bam/boozled";
String[] tokens = dir.split(".+?/(?=[^/]+$)");
// [ "/foo/bar/bam/" "boozled" ]
Old question but I usually use this solution:
import org.apache.commons.io.FilenameUtils;
String fileName = "/abc/defg/file.txt";
String basename = FilenameUtils.getBaseName(fileName);
String extension = FilenameUtils.getExtension(fileName);
System.out.println(basename); // file
System.out.println(extension); // txt (NOT ".txt" !)
Source: http://www.java2s.com/Code/Java/File-Input-Output/Getextensionpathandfilename.htm
such an utility class :
class Filename {
private String fullPath;
private char pathSeparator, extensionSeparator;
public Filename(String str, char sep, char ext) {
fullPath = str;
pathSeparator = sep;
extensionSeparator = ext;
}
public String extension() {
int dot = fullPath.lastIndexOf(extensionSeparator);
return fullPath.substring(dot + 1);
}
public String filename() { // gets filename without extension
int dot = fullPath.lastIndexOf(extensionSeparator);
int sep = fullPath.lastIndexOf(pathSeparator);
return fullPath.substring(sep + 1, dot);
}
public String path() {
int sep = fullPath.lastIndexOf(pathSeparator);
return fullPath.substring(0, sep);
}
}
usage:
public class FilenameDemo {
public static void main(String[] args) {
final String FPATH = "/home/mem/index.html";
Filename myHomePage = new Filename(FPATH, '/', '.');
System.out.println("Extension = " + myHomePage.extension());
System.out.println("Filename = " + myHomePage.filename());
System.out.println("Path = " + myHomePage.path());
}
}
http://docs.oracle.com/javase/6/docs/api/java/io/File.html#getName()
From http://www.xinotes.org/notes/note/774/ :
Java has built-in functions to get the basename and dirname for a given file path, but the function names are not so self-apparent.
import java.io.File;
public class JavaFileDirNameBaseName {
public static void main(String[] args) {
File theFile = new File("../foo/bar/baz.txt");
System.out.println("Dirname: " + theFile.getParent());
System.out.println("Basename: " + theFile.getName());
}
}
What's wrong with your code? Wrapped in a neat utility method it's fine.
What's more important is what to use as separator — the first or last dot. The first is bad for file names like "setup-2.5.1.exe", the last is bad for file names with multiple extensions like "mybundle.tar.gz".
File extensions are a broken concept
And there exists no reliable function for it. Consider for example this filename:
archive.tar.gz
What is the extension? DOS users would have preferred the name archive.tgz. Sometimes you see stupid Windows applications that first decompress the file (yielding a .tar file), then you have to open it again to see the archive contents.
In this case, a more reasonable notion of file extension would have been .tar.gz. There are also .tar.bz2, .tar.xz, .tar.lz and .tar.lzma file "extensions" in use. But how would you decide, whether to split at the last dot, or the second-to-last dot?
Use mime-types instead.
The Java 7 function Files.probeContentType will likely be much more reliable to detect file types than trusting the file extension. Pretty much all the Unix/Linux world as well as your Webbrowser and Smartphone already does it this way.
You can also user java Regular Expression. String.split() also uses the expression internally. Refer http://download.oracle.com/javase/1.4.2/docs/api/java/util/regex/Pattern.html
Maybe you could use String#split
To answer your comment:
I'm not sure if there can be more than one . in a filename, but whatever, even if there are more dots you can use the split. Consider e.g. that:
String input = "boo.and.foo";
String[] result = input.split(".");
This will return an array containing:
{ "boo", "and", "foo" }
So you will know that the last index in the array is the extension and all others are the base.

Categories

Resources