I need to make my program read a file, then take the numbers in the string and sort them into an array. I can get my program to read the file and put it to a string, but that's where I'm stuck. All the numbers are on different lines in the file, but appear as one long number in the string. This is what I have so far:
public static void main(String[] args) {
String ipt1;
Scanner fileInput;
File inFile = new File("input1.dat");
try {
fileInput = new Scanner(inFile);
//Reads file contents
while (fileInput.hasNext()) {
ipt1 = fileInput.next();
System.out.print(ipt1);
}
fileInput.close();
}
catch (FileNotFoundException e) {
System.out.println(e);
}
}
I recommend reading the values in as numeric types using fileInput.nextInt() or whatever type you want them, putting them in an array and using a built in sort like Arrays.sort. Unless I'm missing a more subtle point about the question.
If your task is just to get input from some file and you're sure the file has integers, use an ArrayList.
import java.util.*;
Scanner fileInput;
ArrayList<Double>ipt1 = new ArrayList<Double>();
File inFile = new File("input1.dat");
try {
fileInput = new Scanner(inFile);
//Reads file contents
while (fileInput.hasNext()){
ipt1.add(fileInput.nextDouble()); //Adds the next Double to the ArrayList
System.out.print(ipt1.get(ipt1.size()-1)); //Prints out what you just got.
}
fileInput.close();
}
catch (FileNotFoundException e){
System.out.println(e);
}
//Sorting time
//This uses the built-in Array sorting.
Collections.sort(ipt1);
However, if you DO need to come up with a simple array in the end, but CAN use ArrayLists, you can add the following:
Double actualResult[] = new Double[ipt1.size()]; //Declare array
for(int i = 0; i < ipt1.size(); ++i){
actualResult[i] = ipt1.get(i);
}
Arrays.sort(actualResult[]);
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;
public class SortNumberFromFile {
public static void main(String[] args) throws IOException {
BufferedReader br = null;
try {
System.out.println("Started at " + LocalDateTime.now());
br = new BufferedReader(new FileReader("/folder/fileName.csv"));//Read data from file named /folder/fileName.csv
List<Long> collect = br.lines().mapToLong(a -> Long.parseLong(a)).boxed().collect(Collectors.toList());//Collect all read data in list object
Collections.sort(collect);//Sort the data
writeRecordsToFile(collect, "/folder/fileName.txt");//Write sorted data to file named /folder/fileName.txt
System.out.println("Ended at " + LocalDateTime.now());
}
finally {
br.close();
}
}
public static <T> void writeRecordsToFile(Collection<? extends T> items, String filePath) {
BufferedWriter writer = null;
File file = new File(filePath);
try {
if(!file.exists()) {
file.getParentFile().mkdirs();
file.createNewFile();
}
writer = new BufferedWriter(new FileWriter(filePath, true));
if(items != null && items.size() > 0) {
for(T eachItem : items) {
if(eachItem != null) {
writer.write(eachItem.toString());
writer.newLine();
}
}
}
} catch (IOException ex) {
}finally {
try {
writer.close();
} catch (IOException e) {
}
}
}
}
Related
I am new to java, but not coding. I am trying to figure out java because it's part of my class this term and I am having a really hard problem grasping the idea of it and implementing things in java.
my problem Is that I am not sure if I am correctly using the arraylist to grab data from the scan of the file and input it into a arraylist to sort and print at a later time. I am just having issues picking up on java any help would be great since I am new to java.
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.FileNotFoundException;
import java.util.Scanner;
import java.util.regex.Pattern;
import java.util.ArrayList;
import java.util.*;
public class MissionCount
{
private static ArrayList<String> list = new ArrayList<String>();
// returns an InputStream that gets data from the named file
private static InputStream getFileInputStream(String fileName) throws Exception {
InputStream inputStream;
try {
inputStream = new FileInputStream(new File(fileName));
}
catch (FileNotFoundException e) { // no file with this name exists
inputStream = null;
throw new Exception("unable to open the file -- " + e.getMessage());
}
return inputStream;
}
public static void main(String[] args) {
if (args.length != 1) {
System.out.println("USage: MissionCount <datafile>");
//System.exit(1);
}
try {
System.out.printf("CS261 - MissionCount - Chad Dreher%n%n");
int crewcount = 0;
int misscount = 0;
InputStream log = getFileInputStream(args[0]);
Scanner sc = new Scanner(log);
sc.useDelimiter(Pattern.compile(",|\n"));
while (sc.hasNext()) {
String crewMember = sc.next();
list.add(crewMember);
String mission = sc.next();
list.add(mission);
}
sc.close();
// Add code to print the report here
}catch (Exception e) {
System.out.println("Error: " + e.getMessage());
}
}
}
InputStream log = getFileInputStream(args[0]);
Change that line to as follows :-
File log = new File(args[0])
that should work!
I have this code:
public static void write() throws IOException{
ObjectOutputStream out = new ObjectOutputStream(
new FileOutputStream("ips.txt")
);
for ( int i = 0; i < Main.ipList.length; i++){
out.writeObject(ipList[i]);
}
out.flush();
out.close();
}
Which writes the string array to a text file:
static String[] ipList = {"127.0.0.1", "173.57.51.111"};
I was wondering how it would be possible to read the text file and edit the ipList with the new ips.
If you want to write String objects to a file, it's better to use a FileWriter instead of an ObjectOutputStream. Similarly, use a FileReader to read from the file. See https://docs.oracle.com/javase/tutorial/essential/io/charstreams.html for how to use these Reader objects.
ObjectOutputStream is usually suitable for writing more complex objects that implement the java.io.Serializable interface.
Here's an example:
BufferedReader inputStream = null;
List<String> ipList = new ArrayList<>();
try {
inputStream = new BufferedReader(new FileReader("ips.txt"));
String l;
while ((l = inputStream.readLine()) != null) {
ipList.add(l);
}
} finally {
if (inputStream != null) {
inputStream.close();
}
}
// get an array from the ArrayList
ipArray = ipList.toArray(new String[ipList.size()]);
You can try something like this
package a;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class A {
static String[] ipList = { "127.0.0.1", "173.57.51.111" };
public static void main(String[] args) {
try {
write();
update();
} catch (IOException e) {
System.err.println(e);
}
Arrays.asList(ipList).stream().forEach(System.out::println);
}
// Your method
public static void write() throws IOException {
ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("ips.txt"));
for (int i = 0; i < A.ipList.length; i++) {
out.writeObject(ipList[i]);
}
out.flush();
out.close();
}
public static void update() throws IOException {
List<String> lines = Files.readAllLines(Paths.get(".", "newIps.txt"));
List<String> newIps = new ArrayList<>();
newIps.addAll(Arrays.asList(ipList));
newIps.addAll(lines);
ipList = newIps.toArray(ipList);
}
}
The content of the newIps.txt file is
0.0.0.0
192.168.1.1
The output of the program is
127.0.0.1
173.57.51.111
0.0.0.0
192.168.1.1
Note that Arrays.asList(ipList) returns a bridge list over the array (any changes to the list will be visible for array), so we do a putAll
I am trying to load in a file from my computer with all the words of the dictionary in the file.
When I load the file i put the words into an array of strings.
I then want to eliminate all words that have more than 9 letters in them.
I then want to save the words that are 9 letters or smaller into another separate text file.
When i try to open the new file it only has 9 words in it, yet my print to the screen on eclipse will print the all words of nine or less letters.
Can anyone help!
This is a program that was gave to me as part of the question.
import java.io.*;
public class FileIO{
public String[] load(String file) {
File aFile = new File(file);
StringBuffer contents = new StringBuffer();
BufferedReader input = null;
try {
input = new BufferedReader( new FileReader(aFile) );
String line = null;
int i = 0;
while (( line = input.readLine()) != null){
contents.append(line);
i++;
contents.append(System.getProperty("line.separator"));
}
}
catch (FileNotFoundException ex) {
System.out.println("Can't find the file - are you sure the file is in this location: "+file);
ex.printStackTrace();
}
catch (IOException ex){
System.out.println("Input output exception while processing file");
ex.printStackTrace();
}
finally {
try {
if (input!= null) {
input.close();
}
}
catch (IOException ex) {
System.out.println("Input output exception while processing file");
ex.printStackTrace();
}
}
String[] array = contents.toString().split("\n");
for(String s: array){
s.trim();
}
return array;
}
public void save(String file, String[] array) throws FileNotFoundException, IOException {
File aFile = new File(file);
Writer output = null;
try {
output = new BufferedWriter( new FileWriter(aFile) );
for(int i=0;i<array.length;i++){
output.write( array[i] );
output.write(System.getProperty("line.separator"));
}
}
finally {
if (output != null) output.close();
}
}
}
this is the class i tried to use
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.*;
public class countdown{
public static void main(String args[]){
FileIO reader = new FileIO();
Scanner scan = new Scanner(System.in);
String[] inputs = reader.load("C:/Users/Sony/Documents/dict.csv"); //Reading the File as a String array from a file called dict
String[] input = new String[inputs.length]; //new String array for strings less than 9 letters
for(int i=0;i<inputs.length;i++){
if(inputs[i].length()<=9) { //if string of index i is less than 9
input[i]=inputs[i]; //add it to the new array called input
System.out.println(input[i]); //print line to check
}
}
try{
reader.save("C:/Users/Sony/Documents/dictnew.csv",input);
//this is where i save it to the new file called dictnew.
}catch (Exception e){
System.out.println(e.getClass());
}
}
}
After reading how you want you can split rest logic remains same.
package com.srijan.playground;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class FilterLengthWords {
public static void main(String[] args) throws IOException {
BufferedReader br = null;
BufferedWriter bw = null;
try {
br = new BufferedReader(new FileReader("Sample.txt"));
bw = new BufferedWriter(new FileWriter("Output.txt"));
String tmp = null;
while((tmp=br.readLine())!=null) {
if(tmp.length()<=9) {
bw.write(tmp);
}
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
if(br!=null) {
br.close();
br=null;
}
if(bw!=null){
bw.close();
bw=null;
}
}
}
}
Thanks
I'm using RandomAccessFile to create a database to a text file. Basically I created a normal store using an ArrayList and now i need to output the contents of the store using RandomAccessFile. But I am stuck on how to get the randomAccessFile method to take the student store. Here is my code:
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.RandomAccessFile;
public class MainApp
{
private RandomAccessFile File;
public static void main(String[] args) throws Exception
{
new MainApp().start();
}
public void start()throws Exception
{
StudentStore details = new StudentStore();
Student a = new Student("Becky O'Brien", "DKIT26", "0876126944", "bexo#hotmail.com");
Student b = new Student("Fabio Borini", "DKIT28", "0876136944", "fabioborini#gmail.com");
Student c = new Student("Gaston Ramirez", "DKIT29", "0419834501", "gramirez#webmail.com");
Student d = new Student("Luis Suarez", "DKIT7", "0868989878", "luissuarez#yahoo.com");
Student e = new Student("Andy Carroll", "DKIT9", "0853456788", "carroll123#hotmail.com");
details.add(a);
details.add(b);
details.add(c);
details.add(d);
details.add(e);
details.print();
//Create a file object.
File contactDetailsFile = new File("StudentDetails.txt");
//Open a buffered output stream to allow write to file operations.
PrintWriter out = new PrintWriter(
new BufferedWriter(
new FileWriter(contactDetailsFile)));
out.println(a);
out.println(b);
out.println(c);
out.println(d);
out.println(e);
out.close();
BufferedReader in = new BufferedReader(
new FileReader(contactDetailsFile));
String line = in.readLine();
System.out.println(line);
out.close();
}
/**
* #param args the command line arguments
*/
public void RandomAccessFile(String filename)
{
RandomAccessFile randomAccessFile = null;
try {
//Declare variables that we're going to write
String line1 = "First line\n";
String line2 = "Second line\n";
//Create RandomAccessFile instance with read / write permissions
randomAccessFile = new RandomAccessFile(filename, "rw");
//Write two lines to the file
randomAccessFile.writeBytes(line1);
randomAccessFile.writeBytes(line2);
//Place the file pointer at the end of the first line
randomAccessFile.seek(line1.length());
//Declare a buffer with the same length as the second line
byte[] buffer = new byte[line2.length()];
//Read data from the file
randomAccessFile.read(buffer);
//Print out the buffer contents
System.out.println(new String(buffer));
} catch (FileNotFoundException ex) {
ex.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
} finally {
try {
if (randomAccessFile != null)
randomAccessFile.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
}
In a word, yes.
You will, however, have to re-do your write-to-file part of this solution again. You must read objects back out the same way you wrote them.
From this example, you can see how each member is written using the RandomAccessFile object.
I would suggest that you make the read method from the example return a new Student object.
I was wondering if anyone has logic in java that removes duplicate lines while maintaining the lines order.
I would prefer no regex solution.
public class UniqueLineReader extends BufferedReader {
Set<String> lines = new HashSet<String>();
public UniqueLineReader(Reader arg0) {
super(arg0);
}
#Override
public String readLine() throws IOException {
String uniqueLine;
if (lines.add(uniqueLine = super.readLine()))
return uniqueLine;
return "";
}
//for testing..
public static void main(String args[]) {
try {
// Open the file that is the first
// command line parameter
FileInputStream fstream = new FileInputStream(
"test.txt");
UniqueLineReader br = new UniqueLineReader(new InputStreamReader(fstream));
String strLine;
// Read File Line By Line
while ((strLine = br.readLine()) != null) {
// Print the content on the console
if (strLine != "")
System.out.println(strLine);
}
// Close the input stream
in.close();
} catch (Exception e) {// Catch exception if any
System.err.println("Error: " + e.getMessage());
}
}
}
Modified Version:
public class UniqueLineReader extends BufferedReader {
Set<String> lines = new HashSet<String>();
public UniqueLineReader(Reader arg0) {
super(arg0);
}
#Override
public String readLine() throws IOException {
String uniqueLine;
while (lines.add(uniqueLine = super.readLine()) == false); //read until encountering a unique line
return uniqueLine;
}
public static void main(String args[]) {
try {
// Open the file that is the first
// command line parameter
FileInputStream fstream = new FileInputStream(
"/home/emil/Desktop/ff.txt");
UniqueLineReader br = new UniqueLineReader(new InputStreamReader(fstream));
String strLine;
// Read File Line By Line
while ((strLine = br.readLine()) != null) {
// Print the content on the console
System.out.println(strLine);
}
// Close the input stream
in.close();
} catch (Exception e) {// Catch exception if any
System.err.println("Error: " + e.getMessage());
}
}
}
If you feed the lines into a LinkedHashSet, it ignores the repeated ones, since it's a set, but preserves the order, since it's linked. If you just want to know whether you've seena given line before, feed them into a simple Set as you go on, and ignore those which the Set already contains/contained.
It can be easy to remove duplicate line from text or File using new java Stream API. Stream support different aggregate feature like sort,distinct and work with different java's existing data structures and their methods. Following example can use to remove duplicate or sort the content in File using Stream API
package removeword;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.OpenOption;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.Scanner;
import java.util.stream.Stream;
import static java.nio.file.StandardOpenOption.*;
import static java.util.stream.Collectors.joining;
public class Java8UniqueWords {
public static void main(String[] args) throws IOException {
Path sourcePath = Paths.get("C:/Users/source.txt");
Path changedPath = Paths.get("C:/Users/removedDouplicate_file.txt");
try (final Stream<String> lines = Files.lines(sourcePath )
// .map(line -> line.toLowerCase()) /*optional to use existing string methods*/
.distinct()
// .sorted()) /*aggregrate function to sort disctincted line*/
{
final String uniqueWords = lines.collect(joining("\n"));
System.out.println("Final Output:" + uniqueWords);
Files.write(changedPath , uniqueWords.getBytes(),WRITE, TRUNCATE_EXISTING);
}
}
}
Read the text file using a BufferedReader and store it in a LinkedHashSet. Print it back out.
Here's an example:
public class DuplicateRemover {
public String stripDuplicates(String aHunk) {
StringBuilder result = new StringBuilder();
Set<String> uniqueLines = new LinkedHashSet<String>();
String[] chunks = aHunk.split("\n");
uniqueLines.addAll(Arrays.asList(chunks));
for (String chunk : uniqueLines) {
result.append(chunk).append("\n");
}
return result.toString();
}
}
Here's some unit tests to verify ( ignore my evil copy-paste ;) ):
import org.junit.Test;
import static org.junit.Assert.*;
public class DuplicateRemoverTest {
#Test
public void removesDuplicateLines() {
String input = "a\nb\nc\nb\nd\n";
String expected = "a\nb\nc\nd\n";
DuplicateRemover remover = new DuplicateRemover();
String actual = remover.stripDuplicates(input);
assertEquals(expected, actual);
}
#Test
public void removesDuplicateLinesUnalphabetized() {
String input = "z\nb\nc\nb\nz\n";
String expected = "z\nb\nc\n";
DuplicateRemover remover = new DuplicateRemover();
String actual = remover.stripDuplicates(input);
assertEquals(expected, actual);
}
}
Here's another solution. Let's just use UNIX!
cat MyFile.java | uniq > MyFile.java
Edit: Oh wait, I re-read the topic. Is this a legal solution since I managed to be language agnostic?
For better/optimum performance, it's wise to use Java 8's API features viz. Streams & Method references with LinkedHashSet for Collection as below:
import java.io.IOException;
import java.io.PrintWriter;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.LinkedHashSet;
import java.util.stream.Collectors;
public class UniqueOperation {
private static PrintWriter pw;
enter code here
public static void main(String[] args) throws IOException {
pw = new PrintWriter("abc.txt");
for(String p : Files.newBufferedReader(Paths.get("C:/Users/as00465129/Desktop/FrontEndUdemyLinks.txt")).
lines().
collect(Collectors.toCollection(LinkedHashSet::new)))
pw.println(p);
pw.flush();
pw.close();
System.out.println("File operation performed successfully");
}
here I'm using a hashset to store seen lines
Scanner scan;//input
Set<String> lines = new HashSet<String>();
StringBuilder strb = new StringBuilder();
while(scan.hasNextLine()){
String line = scan.nextLine();
if(lines.add(line)) strb.append(line);
}