I want to create a numbered list, where it shows the index number beside each line. I'm not too sure how to achieve this.
This is the code where i create my list:
public void readFile(Scanner in)
{
inputStudentID = null;
inputMark = 0;
try
{
File file = new File("Marks.txt");
in = new Scanner(file);
}
catch (FileNotFoundException e)
{
System.out.println(e.getMessage());
System.out.println("in " + System.getProperty("user.dir"));
System.exit(1);
}
while (in.hasNextLine())
{
String studentRecord = in.nextLine();
List<String> values = Arrays.asList(studentRecord.split(","));
String inputStudentID = values.get(0);
String sInputMark;
sInputMark = values.get(1);
int inputMark = Integer.parseInt(sInputMark);
addStudent(inputStudentID, inputMark);
}
in.close();
}
Related
copy part like this(from date to date) I am trying to copy only a part of .CSV file based on the first column (Start Date and Time) data looks like (2019-01-28 10:22:00 AM) but the user have to put it like this (2019/01/28 10:22:00)
this is for windows, java opencsv , this is what I found but dont do what I need exaclty :
like this:
int startLine = get value1 from column csv ;
int endLine = get value2 from column csv;
public static void showLines(String fileName, int startLine, int endLine) throws IOException {
String line = null;
int currentLineNo = 1;
// int startLine = 20056;//40930;
// int currentLineNo = 0;
File currentDirectory = new File(new File(".").getAbsolutePath());
String fromPath = currentDirectory.getCanonicalPath() + "\\Target\\part.csv";
PrintWriter pw = null;
pw = new PrintWriter(new FileOutputStream(fromPath), true);
//pw.close();
BufferedReader in = null;
try {
in = new BufferedReader (new FileReader(fileName));
//read to startLine
while(currentLineNo<startLine) {
if (in.readLine()==null) {
// oops, early end of file
throw new IOException("File too small");
}
currentLineNo++;
}
//read until endLine
while(currentLineNo<=endLine) {
line = in.readLine();
if (line==null) {
// here, we'll forgive a short file
// note finally still cleans up
return;
}
System.out.println(line);
currentLineNo++;
pw.println(line);
}
} catch (IOException ex) {
System.out.println("Problem reading file.\n" + ex.getMessage());
}finally {
try { if (in!=null) in.close();
pw.close();
} catch(IOException ignore) {}
}
}
public static void main(String[] args) throws FileNotFoundException {
int startLine = 17 ;
int endLine = 2222;
File currentDirectory = new File(new File(".").getAbsolutePath());
try {
showLines(currentDirectory.getCanonicalPath() + "\\Sources\\concat.csv", startLine, endLine);
} catch (IOException e) {
e.printStackTrace();
}
// pw.println();
}
Common CSV format uses a comma as a delimiter, with quotations used to escape any column entry that uses them within the data. Assuming that your column one data is consistent with the format you posted, and that I wouldn't have to bother with quotations marks therefor, you could read the columns as:
public static void main(String[] args) {
//This is the path to the file you are writing to
String targetPath = "";
//This is the path to the file you are reading from
String inputFilePath = "";
String line = null;
ArrayList<String> lines = new ArrayList<String>();
boolean add = false;
String startLine = "2019/01/28 10:22:00";
String endLine = "2019/01/28 10:30:00";
String addFlagSplit[] = startLine.replace("/", "-").split(" ");
String addFlag = addFlagSplit[0] + " " + addFlagSplit[1];
String endFlagSplit[] = endLine.replace("/", "-").split(" ");
String endFlag = endFlagSplit[0] + " " + endFlagSplit[1];
try(PrintWriter pw = new PrintWriter(new FileOutputStream(targetPath), true)){
try (BufferedReader input = new BufferedReader(new FileReader(inputFilePath))){
while((line = input.readLine()) != null) {
String date = line.split(",")[0];
if(date.contains(addFlag)) {
add = true;
}else if(date.contains(endFlag)) {
break;
}
if(add) {
lines.add(line);
}
}
}
for(String currentLine : lines) {
pw.append(currentLine + "\n");
}
}catch(FileNotFoundException e) {
e.printStackTrace();
}catch(IOException e) {
e.printStackTrace();
}catch(Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) throws IOException {
File currentDirectory = new File(new File(".").getAbsolutePath());
String targetPath = currentDirectory.getCanonicalPath() + "\\Target\\part.csv";
String inputFilePath = currentDirectory.getCanonicalPath() + "\\Sources\\concat.csv";
String line = null;
ArrayList<String> lines = new ArrayList<String>();
boolean add = false;
String startLine = "2019/01/28 10:22:00";
String endLine = "2019/04/06 10:30:00";
try(PrintWriter pw = new PrintWriter(new FileOutputStream(targetPath), true)){
try (BufferedReader input = new BufferedReader(new FileReader(inputFilePath))){
while((line = input.readLine()) != null) {
String date = line.split(",")[0];
if(date.contains(startLine)) {
add = true;
}else if(date.contains(endLine)) {
break;
}
if(add) {
lines.add(line);
}
}
}
for(String currentLine : lines) {
pw.append(currentLine + "\n");
}
}catch(FileNotFoundException e) {
e.printStackTrace();
}catch(IOException e) {
e.printStackTrace();
}catch(Exception e) {
e.printStackTrace();
}
}
I need to input an array of String (very large Strings, about 3000 characters per String). But when I read my input by Scanner, it didn't read all of them. For example, with 100 lines input, it only read to 63rd lines
This is what I got when run it on ideone: http://ideone.com/57uugH
Here is my code:
public class main {
public static void main(String[] args) {
try {
String s;
int t;
ArrayList<String> al = new ArrayList<>();
Scanner sc = new Scanner(System.in);
t = Integer.parseInt(sc.nextLine());
try {
while (sc.hasNextLine()) {
sc.reset();
s = sc.nextLine();
al.add(s);
}
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("Numbers of Index in Arraylist: " + al.size());
} catch (Exception e) {
e.printStackTrace();
}
}
}
Your input has 62 lines and 186 words (61 and 185 excluding first line). If you want to read all words you can use this:
String s;
int t;
ArrayList<String> al = new ArrayList<>();
Scanner sc = new Scanner(new InputStreamReader(System.in));
t = sc.nextInt();
try {
while (sc.hasNext()) {
s = sc.next();
al.add(s);
}
} catch (Exception e) {
e.printStackTrace();
}
In this case your t is not used. If you want to read not more than t (100) words then try this:
String s;
int t;
ArrayList<String> al = new ArrayList<>();
Scanner sc = new Scanner(new InputStreamReader(System.in));
t = sc.nextInt();
try {
while (sc.hasNext() && t-->0) {
s = sc.next();
al.add(s);
}
} catch (Exception e) {
e.printStackTrace();
}
I am working on a program which imports a library from a generated file.
The file generates properly and is found by Scanner. The first line has a single int as written by
pw.println(cdarchive.getNumber());
Elsewhere in the code. This part seems to work fine.
This is the error I'm getting:
Exception in thread "main" java.util.InputMismatchException
at java.util.Scanner.throwFor(Scanner.java:864)
at java.util.Scanner.next(Scanner.java:1485)
at java.util.Scanner.nextInt(Scanner.java:2117)
at java.util.Scanner.nextInt(Scanner.java:2076)
at no.hib.dat102.IO.readFile(IO.java:26)
at no.hib.dat102.Menu.start(Menu.java:34)
at no.hib.dat102.CdArchiveClient.main(CdArchiveClient.java:10)
The line it refers to is
int libSize = in.nextInt();
This is my method:
public class IO {
static final String DELIMITER = "#";
public static CdArchiveADT readFile(String filename) {
Scanner in = null;
CdArchiveADT cda = null;
try
{
File f = new File(filename+".txt");
in = new Scanner(f);
System.out.println(f);
in.useDelimiter(DELIMITER);
int libSize = in.nextInt();
System.out.println("libSize" + libSize);
cda = new CdArchive(libSize);
for (int i=0; i<libSize;i++) {
int inId = in.nextInt();
String inTitle= in.next();
String inArtist = in.next();
String inLabel = in.next();
String inGenre = in.next();
int inYear = in.nextInt();
in.nextLine();
cda.addCd(new CD(inId, inArtist, inTitle, inYear, inGenre, inLabel));
System.out.println("Closing Scanner (input)");
in.close();
}
}
catch (FileNotFoundException e){
System.out.println("Config file not found!");
e.printStackTrace();
}
return cda;
}
EDIT:
This is the method that writes to the file:
public static void writeFile(CdArchiveADT cdarchive, String filename) throws IOException {
PrintWriter pw = null;
File file = null;
try {
file = new File(filename +".txt");
// Create the file if it does not already exist
file.createNewFile();
// Writing metadata
pw = new PrintWriter(new FileWriter(file, false));
pw.println(cdarchive.getNumber());
// Writing data, if CdArchive is not empty
if (cdarchive.getCdTable()[0] != null) {
for (int i = 0; i<cdarchive.getNumber(); i++ ) {
CD c = cdarchive.getCdTable()[i];
pw.print(c.getId()); pw.print(DELIMITER);
pw.print(c.getTitle()); pw.print(DELIMITER);
pw.print(c.getArtist()); pw.print(DELIMITER);
pw.print(c.getLabel()); pw.print(DELIMITER);
pw.print(c.getGenre()); pw.print(DELIMITER);
pw.print(c.getYear()); pw.println(DELIMITER);
}
}
}
catch (FileNotFoundException e)
{
System.out.println("File not found!");
e.printStackTrace();
}
finally
{
if ( pw != null )
{
System.out.println("Closing PrintWriter");
pw.close();
}
}
}
I got a working example:
public static void main(String[] args) {
// write
String delimiter = "#";
StringWriter stringWriter = new StringWriter();
PrintWriter pw = new PrintWriter(stringWriter);
pw.println(3);
for (int i = 0; i < 3; i++) {
pw.print("id " + i);
pw.print(delimiter);
pw.print("titel " + i);
pw.print(delimiter);
pw.print("artist " + i);
pw.println(delimiter);
}
String theString = stringWriter.toString();
System.out.println(theString);
try {
pw.close();
stringWriter.close();
} catch (IOException e) {
// ignore in example
}
// read
Scanner in = new Scanner(theString);
in.useDelimiter("\\s*#\\s*|\\s*\n\\s*"); // add new line as delimiter aswell
int libSize = in.nextInt();
for (int i = 0; i < libSize; i++) {
String inId = in.next();
String inTitle = in.next();
String inArtist = in.next();
in.nextLine();
System.out.println("read: " + inId + ", " + inTitle + ", " + inArtist);
}
in.close();
}
The point is to add new line to the used delimiters aswell
try to use
static final String DELIMITER = "\\s*#\\s*";
Otherwise any leading or trailing spaces will cause that error.
Hi I am trying to write a word counter class on Java. I suppose I am reading a file with scanner from the base folder and printing them to the console. However, first item of file returns with a prefix ÿş or sometimes ?? two question mark. Every item in files are string words. Here is my source code, I could not managed to handle this, so please any help would be appreciated, thanks... (By the way I am using JCreator LE 4.5)
import java.io.*;
import java.util.*;
public class WordCounter implements Comparator<Integer>{
public static Scanner myScanner;
private static int orderNumber = 0;
private static String inputName = "";
private static String outputName = "";
private static LinkedHashMap<String, Integer> dictionary = new LinkedHashMap<String, Integer>();
private static ArrayList<String> words = new ArrayList<String>();
private static SortedSet<String> keys;
private static Scanner in;
public static void main(String[] args) {
myScanner = new Scanner(System.in);
System.out.println("Please enter a file name to read...");
inputName = myScanner.nextLine();
System.out.println("Please enter a file name to write in...");
outputName = myScanner.nextLine();
askForOptions();
readFromFile(inputName);
writeToFile(outputName, orderNumber);
}
private static void readFromFile(String fileName){
try {
in = new Scanner(new File(fileName+".txt"));
while(in.hasNext()){
String lowered = in.next().toLowerCase();
if(!lowered.equals(" ") || !lowered.equals("") || !lowered.equals(null)){
System.out.println(lowered);
int lastInd = lowered.length()-1;
char lastChar = lowered.charAt((lastInd-1));
System.out.println(lastChar);
if (lastChar == '?' || lastChar == ',' || lastChar == '.'){
String newLowered = lowered.substring(0, (lastInd-1));
words.add(newLowered);
}else{
words.add(lowered);
}
}
}
in.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
private static void writeToFile(String fileName, int orderNumber){
for(String word: words) {
if(dictionary.containsKey(word)){
int val = (int) dictionary.get(word);
dictionary.put(word, val+1);
}else{
dictionary.put(word, 1);
}
}
if(orderNumber == 1){
keys = new TreeSet<String>(dictionary.keySet());
try {
FileWriter writer = new FileWriter(fileName+".txt");
for(String key:keys){
writer.write(key + "\t" + dictionary.get(key) + "\n");
}
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}else if(orderNumber == 2){
Comparator<Integer> comp = new Comparator<Integer>() ;
TreeMap<Integer, String> wordsMap = new TreeMap<Integer, String>(comp);
for(Map.Entry<String, Integer> entry:dictionary.entrySet()){
wordsMap.put(entry.getValue(),entry.getKey());
}
try {
FileWriter writer = new FileWriter(fileName+".txt");
for(Map.Entry<Integer, String> entry: wordsMap.entrySet()){
writer.write(entry.getValue() + "\t" + entry.getKey() + "\n");
}
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
private static void askForOptions(){
System.out.println("How do you want the result? \nPress 1 to get result in alphabethic order, \nPress 2 to in frequency order.");
int option = myScanner.nextInt();
if (option == 1){
orderNumber = 1;
System.out.println("Thank you! Good luck...");
}else if(option == 2){
orderNumber = 2;
System.out.println("Thank you! Good luck...");
}else{
System.out.println("Invalid choice! Plese try again...");
askForOptions();
}
}
#Override
public int compare(Integer arg0, Integer arg1) {
if (arg0 == arg1) return 0;
if (arg0 > arg1) return 1;
if (arg0 < arg1) return -1;
return 0;
}
}
ÿş are UTF-16 BOM bytes FF FE printed using Windows 1254 codepage, which is your system default I believe.
To read file correcly, you need to skip BOM, which can be done using Apache Commons IO BOMInputStream wrapper:
try (BOMInputStream bis = new BOMInputStream(new FileInputStream(filename));
Scanner in = new Scanner(bis, bis.getBOMCharsetName() == null
? Charset.defaultCharset().name()
: bis.getBOMCharsetName())) {
// read lines
} catch (IOException e) {
// ...
}
Or you can skip those 2 bytes manually as described in answers for this post.
I have a .dat file that I want to load into a custom array. How do I get it to actually load the data into the array. The data consists of a (String, int, int, double, String).
class CDinventoryItem{
private CDinventoryItem [] inven = new CDinventoryItem[1000];
public CDinventoryItem (String title, int itemNumber, int numberofUnits,
double unitPrice, String genre){
DataInputStream input;
try{
input = new DataInputStream(new FileInputStream("inventory.dat"));
inven = input.read(CDinventoryItem[]); //line I am receiving error on
}
catch ( IOException error ){
JOptionPane.showMessageDialog( null, "File not found",
"" ,JOptionPane.ERROR_MESSAGE);
}
}
}
So now readFile is in its own class...
class readFile {
public CDinventoryItem[] inven;
public readFile(){
BufferedReader in = null;
try {
in = new BufferedReader(new FileReader("inventory.dat"));
String line = null;
int i = 0;
while ((line = in.readLine()) != null) {
// process each line
String[] parts = line.split(",");
String title = parts[0];
int itemNumber = Integer.parseInt(parts[1]);
int numberofUnits = Integer.parseInt(parts[2]);
double unitPrice = Double.parseDouble(parts[3]);
String genre = parts[4];
CDinventoryItem item = new CDinventoryItem(title, itemNumber, numberofUnits,
unitPrice, genre);
//add item to array
inven[i] = item;
i++;
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}}
and I am calling it from my CDinventory class
readFile invenItem = new readFile();
list = new JList(invenItem.inven);
but it gives me a: Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1
on line:
readFile invenItem = new readFile();
Doesn't seem to like me passing the array that way.
You need to read the file line by line. Split each line on , and create a single CDInventoryItem. Add the item to your array.
Also, note that this method should not be in the constructor of CDInventoryItem. Your CDInventoryItem class should not even have an array of CDInventoryItems. All this should be done in a separate class.
Here is some code to get you started:
public void readFile() {
BufferedReader in = null;
try {
in = new BufferedReader(new FileReader("inventory.dat"));
String line = null;
int i = 0;
while ((line = in.readLine()) != null) {
// process each line
String[] parts = line.split(",");
String title = parts[0];
int itemNumber = Integer.parseInt(parts[1]);
int numberOfUnits = Integer.parseInt(parts[2]);
double unitPrice = Double.parseDouble(parts[3]);
String genre = parts[4];
CDinventoryItem item = new CDinventoryItem(title, itemNumber, unitPrice, genre);
//add item to array
inven[i] = item;
i++;
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}