This question already has answers here:
How do I split a string in Java?
(39 answers)
Closed 6 years ago.
I'm working an project where the program is supposed to analyze other project, the other projects are located in a specisfic directory. The projects are named under a standard similar to the following:
Projectname-version-downloadingDate example:
ElasticSearch-1.0-20160417
right now the program can return the whole project name as one string and save it to CSV file, using the following methods:
private String projectName;
public void setProjectName(String projectName){
this.projectName = projectName;
}
public String getProjectName(){
return projectName;
}
and here is the method call for writing the name of the project:
private void writeReport() {
BufferedWriter out = null;
try {
File file = new File("out.csv");
boolean exists = file.exists();
FileWriter fstream = new FileWriter(file, exists /*=append*/);
out = new BufferedWriter(fstream);
if (!exists) {
out.write("File Name;");
out.write(System.getProperty("line.separator"));
}
out.write(String.valueOf(newFiles.getProjectName()) + ";"); //method call
out.write(System.getProperty("line.separator"));
// }
//Close the output stream
out.close();
} catch (Exception e) {
System.err.println("Error: " + e.getMessage());
// return;
}
}
now my question is how can I split the name of the project into three parts and write each one separated in the CSV file?
the project name, the version and the download date? meaning that it should take the project name from the substring located before the first "-" and the version after the first "-" and finally the date after the second "-"?
any tips how to do that?
thanks
Use the string.split method.
String string = "ElasticSearch-1.0-20160417";
String[] parts = string.split("-");
String projectName = parts[0]; // ElasticSearch
String versionNumber= parts[1]; // 1.0
String downloadDate= parts[2]; // 20160417
Related
This question already has answers here:
Modifying existing file content in Java
(4 answers)
Closed 3 years ago.
I m working cucumber with java automation framework , there one directory has one text file which I coded like (Every time it is renaming ) , I want to pick up that new renaming file and after opening that file I want to update some particular data and save it for further code.
Can anyone help me how can I open text file , How can I update and close it again,
want to update particular data (see example below)(There has Name column and Value in second raw , want to update Name data every time with any random string)
Text file data :
Name | DOB | Gender |
Komal | 5-6-1992 | Female
You can't update existing file using Java.
You have to read, modify and write to a new file.
Delete the old file
Rename the new file with old file name.
Below program would replace 4th Column data (Komal) with desired string and We need to pass directory name which would have 1 txt file.
public class MyApplication {
public static void main(String[] args) throws Exception {
getTxtFileWithInADirectory("D:\\Learning\\newyork");
}
static void getTxtFileWithInADirectory(String directoryPath) {
String fileExtension;
File folder = new File(directoryPath);
File[] listOfFiles = folder.listFiles();
for (int i = 0; i < listOfFiles.length; i++) {
if (listOfFiles[i].isFile()) {
fileExtension = listOfFiles[i].getName().substring(listOfFiles[i].getName().lastIndexOf("."), listOfFiles[i].getName().length());
if(fileExtension.contains(".txt")) {
updateTXTFile(listOfFiles[i].getAbsolutePath(),"Poonam");
}
} else {
System.out.println(".txt file not found");
}
}
}
static void updateTXTFile(String fileToBeModified, String newText) {
String oldContent = "";
BufferedReader reader = null;
FileWriter writer = null;
try
{
reader = new BufferedReader(new FileReader(fileToBeModified));
//Reading all the lines of input text file into oldContent
String line = reader.readLine();
while (line != null)
{
oldContent = oldContent + line + System.lineSeparator();
line = reader.readLine();
}
String[] items = oldContent.split("\\|");
String newContent = oldContent.replace(items[3], " "+newText+" ");
writer = new FileWriter(fileToBeModified);
writer.write(newContent);
}catch (Exception e)
{
e.printStackTrace();
}
finally
{
try
{
//Closing the resources
reader.close();
writer.close();
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
}
This question already has answers here:
How to get a file's Media Type (MIME type)?
(28 answers)
Closed 4 years ago.
if no expanded-name, how to get file type(image/audio or video) by java?
I want to write a function like this:
String getFileType(String filePath){
// TODO:...
return type;
}
Use the following code to get the extension of the file:-
public String getFileType(String fileName) {
String extension = "";
String extensionNew = "";
int index = fileName.lastIndexOf(".");
if (index > 0) {
extension = fileName.substring(index + 1);
extensionNew = fileName.substring(index);
}
System.out.println("File extension is: " + extension);
System.out.println("File extension new is: " + extensionNew);
return extensionNew;
}
Otherwise, Apache Common IO is very popular API for file manipulations. Use the following link to download the jar. http://www.java2s.com/Code/Jar/c/Downloadcommonsio24jar.htm Download those jars, and finish it simple as follows:-
import org.apache.commons.io.FilenameUtils;
public class FileExtensionNew {
public static void main(String[] args) {
String extension = "";
String extension2 = "";
try {
extension = FilenameUtils.getExtension("Hello.java"); // return ---> "java"
extension2 = FilenameUtils.getExtension("home/java/Test.jar"); // return ---> "jar"
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("File extension is: " + extension);
System.out.println("File extension is: " + extension2);
}
}
Hope, it will help you. Thanks!
This question already has answers here:
Java String replace not working [duplicate]
(6 answers)
Closed 8 years ago.
public static boolean passwordConfirmed() {
String attempt = JOptionPane.showInputDialog("Password: ");
FileReader fstream = null;
String password = "";
try {
fstream = new FileReader("pass.txt");
BufferedReader in = new BufferedReader(fstream);
password = in.readLine();
password.replace("Password: ", " ");
System.out.println(password);
} catch (IOException e) {
e.printStackTrace();
}
if (attempt.equals(password)) {
System.out.print("True");
return true;
} else System.out.println("false");
return false;
}
Trying to remove "Password: " from the line.
It gets the line "Password: " + text afterwards (Password)
I want to remove the "Password: ", so all i have left is purely the text afterwards.
Always re-assign it.
password = password.replace("Password: ", " ");
Strings are immutable in Java, meaning you can't modify an existing instance of it. By re-assigning it, you'll be capturing the new value of the string into an existing variable.
This question already has an answer here:
Closed 10 years ago.
Possible Duplicate:
Java - Using Jena APi - Get data from RDF file
I'm using Java and Jena API.
I have the class Person with the datatype properties hasFirstName, hasLastName, hasDateOfBirth, hasGender.
Here is how one person is represented in my RDF file.
<rdf:Description rdf:about="http://www.fam.com/FAM#Bruno04/02/1980 ">
<j.0:FAMhasGender>H</j.0:FAMhasGender>
<j.0:FAMhasDateOfBirth>04/02/1980</j.0:FAMhasDateOfBirth>
<j.0:FAMhasLastName>DS </j.0:FAMhasLastName>
<j.0:FAMhasFirstName> Bruno</j.0:FAMhasFirstName>
</rdf:Description>
I'd like to get for each person the firstname, gender, date of birth and write that information in a text file. The problem I have is that it only writes the first woman/man he finds in the rdf file, but there is more than one woman and man.
Can you please explain me how can I solve this?
Thank you very much.
ExtendedIterator instances = onto.person.listInstances();
Individual instance = null;
Individual firstInstance = null;
while (instances.hasNext()) {
instance = (Individual) instances.next();
gen = instance.getPropertyValue(onto.hasGender).toString();
fname = instance.getPropertyValue(onto.hasFirstName).toString();
dd = instance.getPropertyValue(onto.hasDateOfBirth).toString();
writeFile(fname, dd, genr);}
// Write text file
public void writeFile(String fn, String dbir, String gn) {
String fileout = "D:/file1.txt";
String firstName = fn;
String dateB = dbir;
String gender = gn;
BufferedWriter out;
try {
out = new BufferedWriter(new FileWriter(fileout, true));
if (gender.equals("F")) {
out.write("[label= \"" + firstName + " \"\n\n\"D.Naiss:" + dnai1 + "\", " + shape + "]");
} else if (gender.equals("M")) {
out.write("[label= \"" + firstName + " \"\n\n\"D.Naiss:" + dnai1 + "\", " + shape2 + "]");
}
out.newLine();
// flushes and closes the stream
out.close();
} catch (IOException e) {
System.out.println("There was a problem:" + e);
}
}
Your problem has nothing to do with Jena or RDF but is rather a logic error in your coding.
You call writeFile() inside your while loop which opens a new file, writes the current entry and closes the file. So you are repeatedly overwriting your file with a single entry at one time so you will only ever end up with a single person in the file.
You need to refactor the code to open the file once before the while loop, have the writeFile() method simply add to that file (and not close it) and then close the file after the while loop.
Also as #Udo Kilmaschewski pointed out in your apparent duplicate the genr variable is not defined in the code you showed so you don't appear to be correctly passing the gender from your while loop to the writeFile() function.
What's the best way to do it? Should I use the File class and scanner? I've never done it before and can't seem to find a solid guide for it online so I figured I would ask here.
Edit:
The text file I am parsing is 3 columns, the first three are ID NAME BIRTHDATE then actual data.
Edit (code from pastie):
public void readFromFile(File file )
{
try
{
System.out.println("success..");
s = new Scanner(file);
BufferedReader input = new BufferedReader(new FileReader(file));
String jj = null;
while((jj = input.readLine())!=null)
{
String [] words = jj.split("\\t");
String name = "";
String id = "";
String birthdate ="";
for (int i = 3; i<words.length; i+=3)
{
id =words[i];
name = words[i+1];
birthdate=words[i+2];
Person p = new Person(id, name, birthdate);
peopleMap.put(p.id,p);
names.add(p);
System.out.println("New entry added to file: "+name+"\\t"+"ID: "
+id+"\\t"+"Birthdate"+birthdate);
}
}
}
catch(IOException e)
{
}
}
The easiest way depends on the format of the text file. From your other comment, it sounds like the lines are tab separated values. As a beginner you will probably find it simplest to use Scanner. Specifically, Scanner.nextLine(). Couple that with using String.split("\t") to split the data into an array (assuming the format is tab-separated-values).
Simply depends on the format of the text file.
If its simple name value pair then you can use java.util.Properties. for example a.properties could look like:
name=john
city=san jose
date=12 july 2010
then you can load this as:
Properties props = new Properties();
props.load(new FileInputStream("a.properties"));
If format is different than what is supported by java.util.Properties.load() then using java.util.Scanner would be helpful to process it line by line:
File file = new File("data.txt");
try
{
Scanner scanner = new Scanner(file);
while (scanner.hasNextLine())
{
String line = scanner.nextLine();
//Process each line seperately
processLine(line);
}
} catch (FileNotFoundException e)
{
e.printStackTrace();
}
If you are free to say what the syntax / structure of the text file is, then consider making it a Java properties file. Then you can load and save the file with minimal programming effort using the java.util.Properties class.
This is what I like to do in that situation:
Scanner s = new Scanner(file);
Scanner line;
String name;
String date;
int id;
while(s.hasNext()){
line = new Scanner(s.nextLine());
id = line.nextInt();
name = line.next/*String*/();
date = line.next/*String*/();
/* Do something with id, name and date */
}
Maybe there is some exception handling or something like that
(Anyone want to comment on the efficiency of creating many new Scanners?)