I'm supposed to be coding an app that can read names from a hardcoded text file, save them as a string array, then write those names in a different text file but sorted. I believe I have the first two parts down but I'm confused on how to sort the names then write them into a new file.
These is the actual problem I'm working on:
"Take an input file with 10 names in it (hard coded). Write a program to read the file, save the names in a String array and write into a different file names in sorted order. Use Methods appropriately."
BTW I'm a rookie coder, this is what I have so far.
public static void main(String[] args) throws FileNotFoundException {
// TODO code application logic here
readFile();
saveStringArray();
}
public static void readFile() {
File file = new File("/Users/nicoladaaboul/Desktop/Programming/C++, "
+ "HTML5, Java, PHP/Java/Question2/names.txt");
try {
Scanner sc = new Scanner(file);
while (sc.hasNextLine()) {
String i = sc.next();
}
sc.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
public static void saveStringArray() throws FileNotFoundException {
String token1 = "";
Scanner inFile1 = new Scanner(new File("names.txt")).useDelimiter(",\\s*");
List<String> temps = new ArrayList<String>();
while (inFile1.hasNext()) {
token1 = inFile1.next();
temps.add(token1);
}
inFile1.close();
String[] tempsArray = temps.toArray(new String[0]);
Arrays.sort(tempsArray);
for (String s : tempsArray) {
System.out.println(s);
}
}
public static void sortingNames() {
}
public static void writingFile() throws FileNotFoundException {
PrintWriter writer = new PrintWriter("sortedNames.txt");
writer.close();
}
Its important that you break your problem down into instructions.
1. You need to read the file you can use bufferedReader(code below).
2. Create an array(or arraylist) to store your string values.
3. Then as you read each line, store these values in the array.
4. When finished reading the file you then would pass this array to a function that would sort it(Why does my sorting loop seem to append an element where it shouldn't?).
5. Once sorted you simply write this array, to a file.
BufferedReader br = new BufferReader(new FileReader("name.txt"));
int count = 0;
String line;
String[] names = new String[100];
while((line = br.nextLine()) != null){
names[count] = line;
count++;
}
Related
I am currently writing an algorithm that creates an ArrayList from a .txt file, checks it with a loop for duplicates (where the loop should look like this:
Line one is written to new .txt & boolean found is set to true because the string was already found.
Line 2 is written to new .txt etc.
But if two strings are identical, the duplicate, i.e. the second string should just be ignored and continue with the next one).
public class test {
public static void main(String[] args) throws IOException {
String suche = "88 BETRAG-MINUS VALUE 'M'.";
String suche2 = "88 BETRAG-PLUS VALUE 'P'";
boolean gefunden = false;
File neueDatei = new File("C:\\Dev\\xx.txt");
if (neueDatei.createNewFile()) {
System.out.println("Datei wurde erstellt");
}
if (gefunden == false) {
dateiEinlesen(null, gefunden);
ArrayList<String> arr = null;
inNeueDateischreiben(neueDatei, gefunden, arr, suche, suche2);
}
}
public static void dateiEinlesen(File neueDatei, boolean gefunden) {
BufferedReader reader;
String zeile = null;
try {
reader = new BufferedReader(new FileReader("C:\\Dev\\Test.txt"));
zeile = reader.readLine();
ArrayList<String[]> arr = new ArrayList<String[]>();
while (zeile != null) {
arr.add(zeile.split(" "));
zeile = reader.readLine();
}
System.out.println(arr);
} catch (IOException e) {
System.err.println("Error2 :" + e);
}
}
public static void inNeueDateischreiben(File neueDatei, boolean gefunden, ArrayList<String> arr, String suche2,
String suche22) throws IOException {
FileWriter writer = new FileWriter(suche22);
String lastValue = null;
for (Iterator<String> i = arr.iterator(); i.hasNext();) {
String currentValue = i.next();
if (lastValue != null && currentValue.equals(lastValue)) {
i.remove();
{
writer.write(suche2.toString());
gefunden = true;
}
}
writer.close();
}
}
}
Your variable namings (suche2, suche22) makes reading the code difficult.
Other than that, your writing algorithm looks funny. You only compare adjacent lines while duplicate lines could be anywhere. In addition, writer.write only hits when you find a duplicate. Also how you call it and other things don't look right.
Here are some general steps to write this correctly:
Open the file so you can read it line by line.
Create a file writer
Create a set or dictionary like data structure that enables you to look up items in constant time.
For each line that you read do the following:
Look if the line exists in the dictionary.
If not, write it to the new file
If it already exists in the dictionary, skip to step 4.
Add that line to the dictionary for later comparisons and go to step 4.
When the lines are exhausted close both files.
I suggest, you rewrite your code completely as the current version is very difficult to amend.
I'm a beginner in java and I have no clue how to read from a CSV file into 2 ArrayLists maybe using tokens and. Type. (list->Array)
Depending on the token we add to one list or another.
Update: The format of the file is fixed. This is the format:
Andrew,Nick,11,Pen,Apple,Backpack,5500.0,570.0,4700.0
Ex:
Name,Description,55.0,100.0
Name into an ArrayList of String.
55.0 into an ArrayList of Double;
This is my code,im trying to figure out the basic first of all.
public class CSVRead {
public static void main(String[] arg) throws Exception {
BufferedReader CSVFile = new BufferedReader(new FileReader("Auto2.csv"));
String data= CSVFile.readLine();
while (data != null){
String[] dataArray = data.split(",");
for (String item:dataArray) {
System.out.print(item + "\t");
}
System.out.println();
data = CSVFile.readLine();
}
CSVFile.close();
System.out.println();
}
}
You can try the following code. As an example I have taken index zero as the name field and the index six as the double value you need. According to the format you can get the actual field index and add it in to your lists.
public void loadData() throws IOException {
List<String> namesList = new ArrayList<>();
List<Double> someDoubleList = new ArrayList<>();
BufferedReader CSVFile = new BufferedReader(new FileReader("/Users/leon/Desktop/Auto2.csv"));
String data = CSVFile.readLine();
while (data != null) {
String[] dataArray = data.split(",");
// Add the names to string list as the index of it is zero
namesList.add(dataArray[0]);
// Add the double value to double list as the index of it is six.
someDoubleList.add(Double.parseDouble(dataArray[6]));
data = CSVFile.readLine();
}
CSVFile.close();
}
As part of a project I'm working on, I'd like to clean up a file I generate of duplicate line entries. These duplicates often won't occur near each other, however. I came up with a method of doing so in Java (which basically find a duplicates in the file, I stored two strings in two arrayLists and iterating but it was not working because of nested for loops i am getting into the condition manyways.
I need an integrated solution for this, however. Preferably in Java. Any ideas?
List item
public class duplicates {
static BufferedReader reader = null;
static BufferedWriter writer = null;
static String currentLine;
public static void main(String[] args) throws IOException {
int count=0,linecount=0;;
String fe = null,fie = null,pe=null;
File file = new File("E:\\Book.txt");
ArrayList<String> list1=new ArrayList<String>();
ArrayList<String> list2=new ArrayList<String>();
reader = new BufferedReader(new FileReader(file));
while((currentLine = reader.readLine()) != null)
{
StringTokenizer st = new StringTokenizer(currentLine,"/"); //splits data into strings
while (st.hasMoreElements()) {
count++;
fe=(String) st.nextElement();
//System.out.print(fe+"/// ");
//System.out.println("count="+count);
if(count==1){ //stores 1st string
pe=fe;
// System.out.println("first element "+fe);
}
else if(count==5){
fie=fe; //stores 5th string
// System.out.println("fifth element "+fie);
}
}
count=0;
if(linecount>0){
for(String s1:list1)
{
for(String s2:list2){
if(pe.equals(s1)&&fie.equals(s2)){ //checking condition
System.out.println("duplicate found");
//System.out.println(s1+ " "+s2);
}
}
}
}
list1.add(pe);
list2.add(fie);
linecount++;
}
}
}
i/p:
/book1/_cwc/B737/customer/Special_Reports/
/Airbook/_cwc/A330-200/customer/02_Watchlists/
/book1/_cwc/B737/customer/Special_Reports/
/jangeer/_cwc/Crj_200/customer/plots/
/Airbook/_cwc/A330-200/customer/02_Watchlists/
/jangeer/_cwc/Crj_200/customer/06_Performance_Summaries/
/jangeer/_cwc/Crj_200/customer/02_Watchlists/
/jangeer/_cwc/Crj_200/customer/01_Highlights/
/jangeer/_cwc/ERJ170/customer/01_Highlights/
o/p:
/book1/_cwc/B737/customer/Special_Reports/
/Airbook/_cwc/A330-200/customer/02_Watchlists/
/jangeer/_cwc/Crj_200/customer/plots/
/jangeer/_cwc/Crj_200/customer/06_Performance_Summaries/
/jangeer/_cwc/Crj_200/customer/02_Watchlists/
/jangeer/_cwc/Crj_200/customer/01_Highlights/
Use a Set<String> instead of Arraylist<String>.
Duplicates aren't allowed in a Set, so if you just add everyline to it, then get them back out, you'll have all distinct strings.
Performance-wise it's also quicker than your nested for-loop.
public static void removeDups() {
String[] input = new String[] { //Lets say you read whole file in this string array
"/book1/_cwc/B737/customer/Special_Reports/",
"/Airbook/_cwc/A330-200/customer/02_Watchlists/",
"/book1/_cwc/B737/customer/Special_Reports/",
"/jangeer/_cwc/Crj_200/customer/plots/",
"/Airbook/_cwc/A330-200/customer/02_Watchlists/",
"/jangeer/_cwc/Crj_200/customer/06_Performance_Summaries/",
"/jangeer/_cwc/Crj_200/customer/02_Watchlists/",
"/jangeer/_cwc/Crj_200/customer/01_Highlights/",
"/jangeer/_cwc/ERJ170/customer/01_Highlights/"
};
ArrayList<String> outPut = new ArrayList<>(); //The array list for storing output i.e. distincts.
Arrays.stream(input).distinct().forEach(x -> outPut.add(x)); //using java 8 and stream you get distinct from input
outPut.forEach(System.out::println); //I will write back to the file, just for example I am printing out everything but you can write back the output to file using your own implementation.
}
The output when I ran this method was
/book1/_cwc/B737/customer/Special_Reports/
/Airbook/_cwc/A330-200/customer/02_Watchlists/
/jangeer/_cwc/Crj_200/customer/plots/
/jangeer/_cwc/Crj_200/customer/06_Performance_Summaries/
/jangeer/_cwc/Crj_200/customer/02_Watchlists/
/jangeer/_cwc/Crj_200/customer/01_Highlights/
/jangeer/_cwc/ERJ170/customer/01_Highlights/
EDIT
Non Java 8 answer
public static void removeDups() {
String[] input = new String[] {
"/book1/_cwc/B737/customer/Special_Reports/",
"/Airbook/_cwc/A330-200/customer/02_Watchlists/",
"/book1/_cwc/B737/customer/Special_Reports/",
"/jangeer/_cwc/Crj_200/customer/plots/",
"/Airbook/_cwc/A330-200/customer/02_Watchlists/",
"/jangeer/_cwc/Crj_200/customer/06_Performance_Summaries/",
"/jangeer/_cwc/Crj_200/customer/02_Watchlists/",
"/jangeer/_cwc/Crj_200/customer/01_Highlights/",
"/jangeer/_cwc/ERJ170/customer/01_Highlights/"
};
LinkedHashSet<String> output = new LinkedHashSet<String>(Arrays.asList(input)); //output is your set of unique strings in preserved order
}
I have two csv file, main and look.
main file contains a list of word like this:
a,c,e,f
b,d,o,f
and look.csv contain two rows like this:
a,f,j
1,0,1
I want to search for each word of main.csv and find a match in look.csv. if there was a match, i replace word in main.csv by a value that is in the row 2 from look.csv
i write this code
public class lookup {
public static void main(String args[]) throws FileNotFoundException
{
String word;
Scanner main = new Scanner(new File("C:\\Users\\sa\\Desktop\\hotel2\\all.csv"));
main.useDelimiter(",");
Scanner look=new Scanner (new File("C:\\Users\\sa\\Desktop\\comtedad.csv"));
while (main.hasNext())
{
word=main.next() ;
while (look.hasNext()){
if (main.next().equals(look.next())) {//code for replacing}
}
}
main.close();
}}
how can i access to second row of look.scv when two entry were matched?
A few things to note before posting my solution:
there is no easy way to replace the contents of a file while reading it, you have to create a new one and output what you need there
if you want to replace values, then this is good place use a Map
your code implies that the look.csv file contains only 2 lines
The following would achieve what you are looking for, but again, the output is in a different file (you can rename afterwards if you wish to do so) :
public class Main {
public static void main(String[] args) throws Exception {
//1. create Scanners that will look through the CSV files
Scanner main = new Scanner(new File("main.csv"));
Scanner look = new Scanner(new File("look.csv"));
//2. create the final CSV file that will contain both the replaced words and non-replaced words from main.csv
FileWriter replaced = new FileWriter(createReplacedCsv());
//3. store contents of look.csv in a Map
Map<String, String> lookCsvWords = storeLookCsvInSet(look);
//4. Store the contents of the file in a StringBuilder, so you can use the StringBuilder.deleteCharAt(int)
// and .lastIndexOf(String) to delete the last comma
StringBuilder builder = new StringBuilder();
//5. keep track of the line we are on
int line = 0;
//6. iterate through main.csv and search for replaceable words, and write them to replaced.csv if they are found
while (main.hasNext()) {
//search the first line for replaceable chars
String[] wordsInLine = main.nextLine().split(",");
for (String word : wordsInLine) {
if (lookCsvWords.containsKey(word) && line == 0) {
word = lookCsvWords.get(word);
}
builder.append(word).append(",");
}
line ++;
builder.deleteCharAt(builder.lastIndexOf(","));
builder.append("\n");
}
//7. write the contents of the StringBuilder to the file
replaced.write(builder.toString());
replaced.close();
}
/*
* Creates the replaced.csv file if it doesn't exist
*/
private static File createReplacedCsv() throws Exception {
File replacedCsv = new File("replaced.csv");
replacedCsv.createNewFile();
return replacedCsv;
}
/*
* Store the words within look.csv in a Map.
* This method assumes that look.csv has only two lines
*/
private static Map<String, String> storeLookCsvInSet(Scanner lookScanner) throws Exception {
Map<String, String> lookCsvWordMappings = new HashMap<String, String>();
String[] line1Values = lookScanner.nextLine().split(",");
String[] line2Values = lookScanner.nextLine().split(",");
for (int i=0; i<line1Values.length; i++) {
lookCsvWordMappings.put(line1Values[i], line2Values[i]);
}
return lookCsvWordMappings;
}
}
Try first to load look.csv in a Mapping data structure like Map<String,String> like this :
Map<String,String> mapping=new HashMap<String,String>()
Scanner look=new Scanner (new File("C:\\Users\\sa\\Desktop\\look.csv"));
String[] keys=look.nextLine().split(",");
String[] values=look.nextLine().split(",");
for(int i=0;i<keys.length;++i)
mapping.put(keys[i],values[i]);
then write a new file while reading the main file like this ;
Scanner main = new Scanner(new File("C:\\Users\\sa\\Desktop\\hotel2\\all.csv"));
PrintWriter mainOutput = new PrintWriter (new File("C:\\Users\\sa\\Desktop\\hotel2\\all.out.csv"));
while (main.hasNext()){
String[] nextTokens=main.nextLine().split(",");
for(String token:nextTokens)
if(mapping.get(token)!=null)
{
mainOutput .print(mapping.get(token)+",");
}else {
mainOutput .print(token+",");
}
mainOutput .println();
}
mainOutput .close();
For homework, we have to read in a txt file which contains a map. With the map we are supposed to read in its contents and place them into a two dimensional array.
I've managed to read the file into a one dimensional String ArrayList, but the problem I am having is with converting that into a two dimensional char array.
This is what I have so far in the constructor:
try{
Scanner file=new Scanner (new File(filename));
while(file.hasNextLine()){
ArrayList<String> lines= new ArrayList<String>();
String line= file.nextLine();
lines.add(line);
map=new char[lines.size()][];
}
}
catch (IOException e){
System.out.println("IOException");
}
When I print out the lines.size() it prints out 1 but when I look at the file it has 10.
Thanks in advance.
You have to create the list outside the loop. With your actual implementation, you create a new list for each new line, so it will always have size 1.
// ...
Scanner file = new Scanner(new File(filename));
List<String> lines = new ArrayList<String>(); // <- declare lines as List
while(file.hasNextLine()) {
// ...
BTW - I wouldn't name the char[][] variable map. A Map is a totally different data structure. This is an array, and if you create in inside the loop, then you may encounter the same problems like you have with the list. But now you should know a quick fix ;)
Change the code as following:
public static void main(String[] args) {
char[][] map = null;
try {
Scanner file = new Scanner(new File("textfile.txt"));
ArrayList<String> lines = new ArrayList<String>();
while (file.hasNextLine()) {
String line = file.nextLine();
lines.add(line);
}
map = new char[lines.size()][];
} catch (IOException e) {
System.out.println("IOException");
}
System.out.println(map.length);
}