How to get scanner to read pipe delimited txt file in java - java

I've been trying to get a scanner to read and sort a pipe delimited text file using delimiter \|but i cant seem to get it to sort or display the reformatted file. When I open the filechooser it also throws and error when i try to import the scanner. The data in the txt file will be a mixture of strings and ints
Scanner scanner = new Scanner("/n");
scanner.useDelimiter(Pattern.compile("[|\n]"));
JTable JT = new Jtable();
List<Integer> List = new ArrayList<>();
System.out.println(scanner.nextInt());
System.out.println(scanner.nextInt());
File readFile; //creates file variable
JFileChooser jFileChooser_Open = new JFileChooser();
int option = jFileChooser_Open.showOpenDialog(this);
readFile = jFileChooser_Open.getSelectedFile();//instantiates file and
gets selected file from jfilechooser
String line;
try (FileReader inStream = new FileReader(readFile); BufferedReader
inBuffer = new BufferedReader(inStream)) {
//create variable line
while ((line = inBuffer.readLine()) != -1 ) {
while (scanner.hasNext()) {
List.add(line);
List.add(scanner.nextInt());
}
System.out.println(List);
}
} catch (IOException ex) {
Logger.getLogger(NewJFrame.class.getName()).log(Level.SEVERE,null, ex);
}
Also I want to get the newly formatted string to be displayed in my table or a text area. But if you guys could help me get it to print to the console, then I would greatly appreciate it.

Related

How to use JFrame to output file content in system console output?

I am using JFrame Java Swing for a piece of code shown below:
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
String filename = (jTextField1.getText());
if (filename.endsWith(".log")) {
Scanner inFile1 = new Scanner(filename).useDelimiter(";");
List<String> temps = new ArrayList<String>();
// while loop
while (inFile1.hasNext()) {
// find next line
String token1 = inFile1.next();
temps.add(token1);
}
inFile1.close();
String[] tempsArray = temps.toArray(new String[0]);
for (String s : tempsArray) {
System.out.println(s);
}
This code works but it only displays the file name as the file name itself (e.g. If my file name = lalala.txt, the output in console would be lalala.txt) I have tried this code but it does not display the contents inside the file. How do I go about displaying the contents in the file while using JFrame as my GUI in my console output? My GUI consist of a text field which will display the file name and when I click the jButton2, I want the button to show the the content of the file instead of the file name by itself. It runs perfectly fine but it is not what I want for my output.
You are using:
new Scanner(filename).useDelimiter(";");
Which in turn is reading the data from the string filename. Instead use:
new Scanner(new File(filename)).useDelimiter(";");
Simply use:
try
{
BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream(new File("absolute path to your text file...")),"UTF8"));
String buf;
while ((buf = in.readLine()) != null)
{
System.out.println(buf);
}
in.close();
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}

FileWriter and PrintWriter won't output to file

I have this code
public User createnewproflie() throws IOException
{
FileWriter fwriter = new FileWriter("users.txt",true); //creates new obj that permits to append text to existing file
PrintWriter userfile = new PrintWriter(fwriter); //creates new obj that prints appending to file as the arg of the obj is a pointer(?) to the obj that permits to append
String filename= "users.txt";
Scanner userFile = new Scanner(filename); //creates new obj that reads from file
User usr=new User(); //creates new user istance
String usrname = JOptionPane.showInputDialog("Please enter user name: "); //acquires usrname
userfile.println("USER: "+usrname+"\nHIGHSCORE: 0\nLASTPLAY: 0"); //writes usrname in file
userfile.flush();
usr.setName(usrname); //gives usr the selected usname
return usr;
}
and it doesn't output on the file... can someone help please?
i knew that flush would output all of the buffered text but it doesn't seem to work for some strange reason...
You can use a String with a FileWriter but a Scanner(String) produces values scanned from the specified string (not from a File). Pass a File to the Scanner constructor (and it's a good idea to pass the same File to your FileWriter). And you need to close() it before you can read it; maybe with a try-with-resources
File f = new File("users.txt");
try (FileWriter fwriter = new FileWriter(f,true);
PrintWriter userfile = new PrintWriter(fwriter);) {
// ... Write stuff to userfile
} catch (Exception e) {
e.printStackTrace();
}
Scanner userFile = new Scanner(f);
Finally, I usually prefer something like File f = new File(System.getProperty("user.home"), "users.txt"); so that the file is saved in the user home directory.

PrintWriter program

Im trying to write a program that will ask for the name of an input file and an output file. It will open the input file and create the output file. It will then read the input file and make a double-spaced copy of the input in the output file.
public class ProgramTest
public static void main (String[] args )
{
Scanner keyboard = new Scanner(System.in);
System.out.println("where to read?");
String in = keyboard.nextLine();
System.out.println("where to write?");
String out = keyboard.nextLine();
Scanner scanner = new Scanner(new File(in));
PrintWriter outputFile = new PrintWriter(out);
}
Thats what I have so far. What I dont know is how to make it do the last part to read the input file and make a double-spaced copy of the input in the output file.
well you can start by reading in the file?
private static void readFile(String inputFile) {
File file = new File(inputFile);
try {
Scanner scan = new Scanner(file);
//for example String s = scan.next(); would store next word
//doulbe d = scan.nextDouble(); would grab next double
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Once you read in the file sore the lines/numbers into variables?? Should not be to hard work with the read file i provided. Also remember what should you read in first ints or strings?

Unable to import data into 2D array

I am trying to create a method that will import data into 2 dimensional array. But somehow my method doesn't work and I found out that the code went wrong after the line:
while (dataScan.hasNext())
Example of .txt file intending for import:
##mm1.0
RowCount=10
--/20140925/Grocery/Supermarket/-5.23/600.00
--/20141013/Car Maintenance/Changing Tires/-200.00/500.00
I want to have the code the read each of them into array, if the line starts with "--"
public TablePanel()
{
data = new Object[10][5];
}
public void openData()
{
//Initializing Variables and set up directory
fileChooser = new JFileChooser(userDirectory);
//Set File Filter
fileChooser.setFileFilter(filter);
//It will return positive if user decides to save
//null means that the dialog won't be open according
//to specific Frame
int valReturn = fileChooser.showOpenDialog(null);
try { //Need to catch IO Exception here
if (valReturn == JFileChooser.APPROVE_OPTION) {
//Get the selected file into the File
//and initializing the BufferReader to read the content
File file = fileChooser.getSelectedFile();
BufferedReader bufferR = new BufferedReader(new FileReader(file));
//Inputting it into Scanner class for parsing tokens
Scanner fileScan = new Scanner(bufferR);
//Perform the following as long as Scanner class has next
String currentLine;
String dataLine;
Scanner dataScan;
//rowData is for importing data and counting rows
int rowData = 0;
while (fileScan.hasNext())
{
//Putting it into current line
currentLine = fileScan.nextLine();
//Perform the following if the line starts with "--"
if (currentLine.regionMatches(0, "--", 0, 2))
{
//cutting the "--" from the line
dataLine = currentLine.substring(1);
dataScan = new Scanner(dataLine);
//Separate them by "/"
dataScan.useDelimiter("/");
//putting data into data[][]
//Some problem with the following loops
while (dataScan.hasNext())
{
for (int colData = 0; colData < data[0].length; rowData++)
data[rowData][colData] = dataScan.next();
} //End of importing data per line
//increasing rowData by one
rowData++;
} //End of data[][] import loop
}
The problem is because your fileScanner is based on the default WhiteSpace Pattern
Scanner fileScan = new Scanner(bufferR); //Replace this with
Scanner fileScan = new Scanner(bufferR, Pattern.compile(System.lineSeparator()); //Java7

extract matched line from text file

a:b:c:d:e
bb:cc:dd:ee:ff
ccc:ddd:eee:fff:ggg
I have a textfile content above. I am trying to compare my user input with the text file. For example
cc:dd
When it is found, I need to retrieve the entire line. How can I retrieve the line which my user input? I have tried using while(scanner.hasNext()) but I could not get my desire outcome.
With standard Java libraries:
File file = new File("file.txt");
String word = "abc";
Scanner scanner = null;
try {
scanner = new Scanner(file);
} catch(FileNotFoundException e) {
//handle this
}
//now read the file line by line
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
if(line.contains(word)) {
System.out.println(line);
}
}
scanner.close();

Categories

Resources