如何用java读取一个txt 文件内的内容并通过封装对象的set方法保存到对象里

如何用java读取一个txt 文件内的内容并通过封装对象的set方法保存到对象里

2个回答

 另外编写一个类
class 你的类
{
private String text;
public void setText(String s) { text = s; }
public String getText() { return text; }
}
 String s = "";
try {
                String encoding="GBK";
                File file=new File(filePath);
                if(file.isFile() && file.exists()){ //判断文件是否存在
                    InputStreamReader read = new InputStreamReader(
                    new FileInputStream(file),encoding);//考虑到编码格式
                    BufferedReader bufferedReader = new BufferedReader(read);
                    String lineTxt = null;
                    while((lineTxt = bufferedReader.readLine()) != null){
                       s += lineTxt + "\r\n";
                    }
                    read.close();
        }else{
            System.out.println("找不到指定的文件");
        }
        } catch (Exception e) {
            System.out.println("读取文件内容出错");
            e.printStackTrace();
        }
                你的类 c = new 你的类();
                c.setText(s);


caozhy
贵阳老马马善福专业维修游泳池堵漏防水工程 回复qq_38087620: 不客气
接近 3 年之前 回复
qq_38087620
qq_38087620 问题已经解决了!谢谢你了!
接近 3 年之前 回复
Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
其他相关推荐
java读取xml,将读到的数据存放到对象中,再按照一定条件写入xml,从而生成动态菜单

做eclipse插件开发,菜单项的配置是在plugin.xml中是写死的,现在想做成动态菜单的形式。中间写一个类,这个类可以读取一个xml配置文件,然后可以有一些方法把提取过的数据和plugin.xml联系起来,通过这个类来动态的配置eclipse的菜单。我的想法是把读到的xml文件的内容封装到java的对象中,返回值是一个集合类型,然后我就不知道怎么做了。 图片是展示效果: ![图片说明](https://img-ask.csdn.net/upload/201609/01/1472719954_312637.png) ``` 下面是我们找的一些相关资源: [](http://dom4j.sourceforge.net/dom4j-1.6.1/guide.html "") 这是我自己写的demo: package testforxybc; public class UserInfo { private String name; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } private String password; } package testforxybc; import java.beans.XMLDecoder; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.util.ArrayList; import java.util.List; public class UserInfoController { public static void main(String args[]) { List<UserInfo> objList = null; try { objList = UserInfoController.objectXMLDecoder("outxml.xml"); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } for (UserInfo userInfo : objList) { System.out.println(userInfo.getName()); System.out.println(userInfo.getPassword()); } } public static List<UserInfo> objectXMLDecoder(String objSource) throws FileNotFoundException,IOException,Exception { List<UserInfo> objList = new ArrayList<UserInfo>(); File fin = new File(objSource); FileInputStream fis = new FileInputStream(fin); XMLDecoder decoder = new XMLDecoder(fis); Object obj = null; try { while( (obj = decoder.readObject()) != null) { objList.add((UserInfo) obj); } } catch (Exception e) { // TODO Auto-generated catch block } fis.close(); decoder.close(); return objList; } } <?xml version="1.0" encoding="UTF-8"?> <?eclipse version="3.4"?> <plugin> <extension point="org.eclipse.ui.commands"> <category name="Inoherb Category" id="com.uds.inoherb.commands.category"> </category> <command name="法规标准库" categoryId="com.uds.inoherb.commands.category" id="com.uds.inoherb.commands.regulatoryStandards"> </command> <command name="产品标准" categoryId="com.uds.inoherb.commands.category" id="com.uds.inoherb.commands.productStandard"> </command> <command name="禁限用清单" categoryId="com.uds.inoherb.commands.category" id="com.uds.inoherb.commands.prohibitedList"> </command> <command name="全成分" categoryId="com.uds.inoherb.commands.category" id="com.uds.inoherb.commands.fullComposition"> </command> <command name="原料库" categoryId="com.uds.inoherb.commands.category" id="com.uds.inoherb.commands.rawMaterial"> </command> <command name="油脂类" categoryId="com.uds.inoherb.commands.category" id="com.uds.inoherb.commands.fadAndOil"> </command> <command name="乳化剂类" categoryId="com.uds.inoherb.commands.category" id="com.uds.inoherb.commands.emulsifier"> </command> <command name="香精类" categoryId="com.uds.inoherb.commands.category" id="com.uds.inoherb.commands.parfum"> </command> <command name="活性物类" categoryId="com.uds.inoherb.commands.category" id="com.uds.inoherb.commands.actives"> </command> </extension> <extension point="org.eclipse.ui.handlers"> <handler commandId="com.uds.inoherb.commands.regulatoryStandards" class="com.uds.inoherb.handlers.SampleHandler"> </handler> <handler commandId="com.uds.inoherb.commands.rawMaterial" class="com.uds.inoherb.handlers.SampleHandler"> </handler> <handler commandId="com.uds.inoherb.commands.productStandard" class="com.uds.inoherb.handlers.SampleHandler"> </handler> <handler commandId="com.uds.inoherb.commands.fadAndOil" class="com.uds.inoherb.handlers.SampleHandler"> </handler> </extension> <extension point="org.eclipse.ui.bindings"> <key commandId="com.uds.inoherb.commands.sampleCommand" contextId="org.eclipse.ui.contexts.window" sequence="M1+6" schemeId="org.eclipse.ui.defaultAcceleratorConfiguration"> </key> </extension> <extension point="org.eclipse.ui.menus"> <menuContribution locationURI="menu:org.eclipse.ui.main.menu?after=additions"> <menu label="企业电子数据库" id="com.uds.inoherb.menus.sampleMenu"> <menu label="法规标准库" id="com.uds.inoherb.menus.sampleMenu2"> <command commandId="com.uds.inoherb.commands.productStandard" id="com.uds.inoherb.menus.productStandard"> </command> <command commandId="com.uds.inoherb.commands.prohibitedList" id="com.uds.inoherb.menus.prohibitedList"> </command> <command commandId="com.uds.inoherb.commands.fullComposition" id="com.uds.inoherb.menus.fullComposition"> </command> </menu> <menu label="原料库" id="com.uds.inoherb.menus.sampleMenu3"> <command commandId="com.uds.inoherb.commands.fadAndOil" id="com.uds.inoherb.menus.fadAndOil"> </command> <command commandId="com.uds.inoherb.commands.emulsifier" id="com.uds.inoherb.menus.emulsifier"> </command> <command commandId="com.uds.inoherb.commands.parfum" id="com.uds.inoherb.menus.parfum"> </command> <command commandId="com.uds.inoherb.commands.actives" id="com.uds.inoherb.menus.actives"> </command> </menu> </menu> </menuContribution> </extension> </plugin> ```

Java如何设计数据库记录到对象的映射的

Java如何设计数据库记录到对象的映射的,datamapper和recordactive又扮演了什么角色? 刚刚和同事聊天,同事是工作近十年的HTML5前端工程师,对Java后端也有很深造诣。我是入坑不久的菜鸟。今天我在浏览MyBatis源码时,问道:“如何才能简单快速读取MyBatis源码?” 同事回答我说:“首先,带着问题去看,然后根据Java的设计模式,去理解源码的实现和设计。”之后他和我谈到数据库记录到对象的映射,告诉我Datamapper和recordactive是很好的两种可以用于关系映射的架构设计。 我在网上搜了一下,没有看到太有用的信息,希望大神能解答一下。多谢。

java单元测试时jar读取项目中properties

我的项目中引用同事的jar,这个jar中读取了我项目中的properties,我的properties里的value是从pom中获取的,这时问题出现了 jar只能读取properties中pom还没有注入时的value,也就是${value}形式。但我项目中自身的获取properties的代码可以成功获取pom注入后的value。这是什么问题?两个现象的区别就是一个是从jar中获取,一个是本地程序获取。

通过FormData对象使用ajax实现异步上传图片,后端(JAVA)的获取后解析的问题?

网上查了很多办法都没有实现异步上传,使用HTML5的FormData对象可以使用ajax异步上传图片。那么问题来了,发给了后端怎么接收和解析呢? 尝试了很多方法,最后通过发现可以使用request的输入流【InputStream in=request.getInputStream();】获得发送的图片字节码。但是当我读取这个流时,读取后保存的图片字节码里会多出一些文字的字节码,导致图片无法正常识别。如图所示。 ![原图片的编码](https://img-ask.csdn.net/upload/201703/30/1490811014_921731.png) / / / / ![通过读取输入流保存后图片的编码](https://img-ask.csdn.net/upload/201703/30/1490811030_453151.png) 通过FormData发送的图片编码开头多了4列,这4列编码记录了该图片的一些信息,测试上传不同的图片这些编码长度不一样,但是都是4列(如果FormData对象还添加了其他属性,会在图片编码的末尾显示,我这里没有添加其他的属性),可以看到从绿色箭头开始的部分都是相同。通过删除这4列编码后图片也确实能正常显示。 ## 现在是想在保存图片时能够获取图片的信息(就是前面4列编码),并且不让它写入保存的文件中。不知道有没有大神能提供一个好的办法。

求帮助 java从properties中解析字符串 生成对象

data={class=S1,name=11,age=11,math=12,eng=33,chinese=100;class=S1,name=12,age=12,math=120,eng=33,chinese=10;class=S1,name=13,age=13,math=130,eng=330,chinese=10;class=S2,name=21,age=21,math=22,eng=222,chinese=55,phy=300;class=S2,name=22,age=22,math=212,eng=220,chinese=55,phy=30;class=S2,name=23,age=23,math=21,eng=22,chinese=55,phy=3;class=S3,name=33,age=33,math=31,eng=32,chinese=355,phy=333,bio=400;}里面有三个类,每个类的属性个数也不一样,怎么解析然后生成对象。

Flex与Java混合项目中使用FileInputStream读取文件的问题

<p>在eclipse里面建立的flex与java混合工程,结构如下:</p> <p>Test</p> <p>  - bin-dibug</p> <p>  - flex-libs</p> <p>  - flex-src</p> <p>       - 123.xls</p> <p>       -Test.mxml</p> <p>  - html-template</p> <p>  - src </p> <p>      - readBean.java</p> <p>      - read.java</p> <p>  - WebContent</p> <p>  - .classpath</p> <p> </p> <p>read.java读取excel文件,把每行作为readBean的对象封装到ArrayList里面,然后通过remoting-config.xml传到Test.mxml,Test.mxml将数据显示到DataGrid里面。</p> <p> </p> <p> </p> <p>read.java代码如下:</p> <p>public ArrayList readExcel() {   <br>  al = new ArrayList();<br>  // 创建对excel文件的索引<br>  HSSFWorkbook workbook;<br>  try {<br>   workbook = new HSSFWorkbook(new FileInputStream("d://Test/flex-src/123.xls"));<br> …………</p> <p> </p> <p>ArrayList  al是用来存放readBean对象的,flex端用arrayCollection接受的。</p> <p> </p> <p> </p> <p>现在问题是我想读取excel的时候用<span style="color: #ff0000;"><strong>相对路径</strong></span>,不知道应该怎么写?123.xls是在flex-src下的。</p> <p> </p> <p>谢谢!!</p> <p>email:<a href="mailto:876787699@qq.com">876787699@qq.com</a></p>

POI 如何读取EXcel表,之后如何存入List集合中

FileInputStream fis = new FileInputStream( "E:\\215e_2016-11-28-15-06-00.xls"); HSSFWorkbook wb = new HSSFWorkbook(fis); System.out.println(wb); // 获取整个excel有多少个sheet HSSFSheet sheet = wb.getSheetAt(0); System.out.println(sheet); // 总行数 int rowNum = sheet.getPhysicalNumberOfRows(); System.out.println(rowNum); // 第一行 int sheetCount = wb.getNumberOfSheets(); System.out.println(sheetCount); for (int i = 0; i < sheetCount; i++) { sheet = wb.getSheetAt(i); rowNum = sheet.getPhysicalNumberOfRows(); int cellNum = sheet.getRow(0).getPhysicalNumberOfCells(); for (int j = 0; j < rowNum; j++) { HSSFRow row = sheet.getRow(j); System.out.println(row); for (short k = 0; k < cellNum; k++) { HSSFCell cell = row.getCell(k); System.out.println(cell); if (cell.getCellType() == HSSFCell.CELL_TYPE_STRING) { System.out.println(cell.getStringCellValue()); } else if (cell.getCellType() == HSSFCell.CELL_TYPE_NUMERIC) { System.out.println(cell.getNumericCellValue()); } else if (cell.getCellType() == HSSFCell.CELL_TYPE_BOOLEAN) { System.out.println(cell.getBooleanCellValue()); } else if (cell.getCellType() == HSSFCell.CELL_TYPE_BLANK) { System.out.println("NULL"); } else { System.out.println(cell.getDateCellValue()); } } } } }

用面向对象的思想实现学生成绩排名功能,成绩按降序排列成绩相同用升序排列

是实现一个排名功能,要求用面向对象的思想,最好用c++实现,最后期望输出的结果是 成绩按降序排列,成绩相同时按学号的升序排列

调对方指定webservice接口,取出自己的数据以xml形式返回

第一次接触接口 ,对方给了我两个资料,一个说明,main.java 就是让我取出我们数据库中的数据,name不变,根据name取出数据存入value写成xml,在线等大神帮助 1.说明: 功能:数据归档 方法定义: int archive(String username,String password,String objectXml, String params) 参数说明: Username:数据归档的用户名。 Password:数据归档的密码。 objectXml:归档数据的XML形式,示例如下: <?xml version="1.0" encoding="GBK"?> ![图片说明](https://img-ask.csdn.net/upload/201611/07/1478528985_615457.jpg) params:归档参数信息,请保持空字符串 返回值: 归档的状态。 状态说明: 1:代表归档成功,2:代表登录失败,3:代表xml解析失败,4:代表数据唯一性检测失败,5:代表必填项为空,6:代表字段值类型不正确 7:代表不符合规定的值范围,8:代表格式校验不正确。 下面是方法: package cn.csg.soa.dagl; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class Main { /** * @param args * @throws IOException */ public static void main(String[] args) throws IOException { // TODO Auto-generated method stub ReferArchiveService referArchiveService = new ReferArchiveServiceImplService() .getReferArchiveServiceImplPort(); File f = new File("E:/Archivedata.xml"); FileInputStream in = new FileInputStream(f); byte b[] = new byte[(int) f.length()]; // 创建合适文件大小的数组 in.read(b); // 读取文件中的内容到b[]数组 in.close(); System.out.println(new String(b)); referArchiveService.archive("gly", "123qwe!@#", new String(b), ""); System.out.println(new String(b)); System.out.println(new String(b)); } }

代码如下,我想问一下怎么封装list

try { File excelFile2 = new File("C:\\Users\\Administrator\\Desktop\\luyan/LTE逻辑站点查询_2015070815.xlsx"); // 创建文件对象 FileInputStream in = new FileInputStream(excelFile2); // 文件流 ExcelUtil.checkExcelVaild(excelFile2); Workbook workbook=ExcelUtil.getWorkbok(in, excelFile2);//读取excel文件获取Workbook workbook.getNumberOfSheets(); //System.out.println("Sheet的数量 ="+sheetCount); Sheet sheet = workbook.getSheetAt(0);// 遍历第一个Sheet System.out.println("数据量2"+sheet.getLastRowNum()); Row row=sheet.getRow(0); System.out.println(row.getCell(0)+","+row.getCell(1)+","+row.getCell(2)+"," +row.getCell(3)+","+row.getCell(14)+","+row.getCell(15)+","+row.getCell(21)+","+row.getCell(25)); for(int i=1;i<1000;++i){ Row trow2=sheet.getRow(i); Cell name=trow2.getCell(0); Cell city=trow2.getCell(1); Cell netWork_type =trow2.getCell(2); Cell Site_type =trow2.getCell(3); Cell longitude=trow2.getCell(14); Cell latitude=trow2.getCell(15); Cell manufacturers =trow2.getCell(21); Cell Station_name=trow2.getCell(25); list.add(Cell); System.out.println(trow2.getCell(0)+","+trow2.getCell(1)+","+trow2.getCell(2)+"," +trow2.getCell(3)+","+trow2.getCell(14)+","+trow2.getCell(15)+","+trow2.getCell(21)+","+trow2.getCell(25)); } System.out.println(list+"222222222222"); } catch (Exception e) { System.out.println("出错"+e.toString()); }

为什么我自制的andriod词典一输入就退出

package com.aaaa.aaaa; import java.io.File; import java.io.FileOutputStream; import java.io.InputStream; import android.os.Bundle; import android.text.Editable; import android.text.TextWatcher; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.widget.AutoCompleteTextView; import android.widget.Button; import android.widget.CursorAdapter; import android.widget.TextView; import android.app.Activity; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; public class MainActivity extends Activity implements OnClickListener, TextWatcher { // 定义数据库的存放路径 private final String DATABASE_PATH = android.os.Environment .getExternalStorageDirectory().getAbsolutePath() + "/dictionary"; // 用户输入文本框 private AutoCompleteTextView word; // 定义数据库的名字 private final String DATABASE_FILENAME = "dictionary.db"; private SQLiteDatabase database; private Button searchWord; // 用户显示查询结果 private TextView showResult; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // 打开数据库 database = openDatabase(); searchWord = (Button) findViewById(R.id.searchWord); word = (AutoCompleteTextView) findViewById(R.id.word); // 绑定监听器 searchWord.setOnClickListener(this); word.addTextChangedListener(this); showResult = (TextView) findViewById(R.id.result); } public class DictionaryAdapter extends CursorAdapter { private LayoutInflater layoutInflater; public DictionaryAdapter(Context context, Cursor c, boolean flags) { super(context, c, flags); layoutInflater = (LayoutInflater) context .getSystemService(Context.LAYOUT_INFLATER_SERVICE); } @Override public CharSequence convertToString(Cursor cursor) { return cursor == null ? "" : cursor.getString(cursor .getColumnIndex("_id")); } // 生成新的选项 @Override public View newView(Context context, Cursor cursor, ViewGroup parent) { View view = layoutInflater.inflate(R.layout.word_list_item, null); setView(view, cursor); return view; } // 绑定选项到列表中 @Override public void bindView(View view, Context context, Cursor cursor) { setView(view, cursor); } // 将单词信息显示到列表中 private void setView(View view, Cursor cursor) { TextView tvWordItem = (TextView) view; tvWordItem.setText(cursor.getString(cursor.getColumnIndex("_id"))); } } // 打开数据库 private SQLiteDatabase openDatabase() { try { // 获得dictionary.db文件的绝对路径 String databaseFilename = DATABASE_PATH + "/" + DATABASE_FILENAME; File dir = new File(DATABASE_PATH); // 如果目录不存在,则创建这个目录 if (!dir.exists()) { dir.mkdir(); } // 如果在/sdcard/dictionary目录中不存在 // dictionary.db文件,则从res\raw目录中复制这个文件到 // SD卡的目录(/sdcard/dictionary) if (!(new File(databaseFilename)).exists()) { // 获得封装dictionary.db文件的InputStream对象 InputStream is = getResources().openRawResource( R.raw.dictionary); FileOutputStream fos = new FileOutputStream(databaseFilename); byte[] buffer = new byte[8192]; int count = 0; // 开始复制dictionary.db文件 while ((count = is.read(buffer)) > 0) { fos.write(buffer, 0, count); } // 关闭文件流 fos.close(); is.close(); } // 打开/sdcard/dictionary目录中的dictionary.db文件 SQLiteDatabase database = SQLiteDatabase.openOrCreateDatabase( databaseFilename, null); return database; } catch (Exception e) { e.printStackTrace(); } return null; } @Override public void onClick(View v) { // 查询指定的单词 String sql = "select chinese from t_words where english=?"; Cursor cursor = database.rawQuery(sql, new String[] { word.getText() .toString() }); String result = "未找到该单词."; // 如果查找单词,显示其中文的意思 if (cursor.getCount() > 0) { // 必须使用moveToFirst方法将记录指针移动到第1条记录的位置 cursor.moveToFirst(); result = cursor.getString(cursor.getColumnIndex("chinese")) .replace("&", "&"); } // 将结果显示到TextView中 showResult.setText(word.getText() + "\n" + result.toString()); } @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { } @Override public void afterTextChanged(Editable s) { // 必须将english字段的别名设为_id Cursor cursor = database.rawQuery( "select english as _id from t_words where english like ?", new String[] { s.toString() + "%" }); // 新建新的Adapter DictionaryAdapter dictionaryAdapter = new DictionaryAdapter(this, cursor, true); // 绑定适配器 word.setAdapter(dictionaryAdapter); } }

java错误:Connection refused:connect

这是我主界面,我想在这点开文件,然后可以发送给连接的人,目前的测试就是自己给自己发。 package com.fastSendFile; import java.awt.BorderLayout; import java.awt.Dimension; import java.awt.FlowLayout; import java.awt.datatransfer.DataFlavor; import java.awt.datatransfer.Transferable; import java.awt.dnd.DnDConstants; import java.awt.dnd.DropTarget; import java.awt.dnd.DropTargetAdapter; import java.awt.dnd.DropTargetDropEvent; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.io.File; import java.io.IOException; import java.net.InetAddress; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Vector; import javax.swing.BoxLayout; import javax.swing.JButton; import javax.swing.JCheckBox; import javax.swing.JFileChooser; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JSplitPane; import javax.swing.JTable; import javax.swing.JTextArea; import javax.swing.JTextField; import javax.swing.table.DefaultTableColumnModel; import javax.swing.table.DefaultTableModel; import javax.swing.table.JTableHeader; public class SendWindow { // private static final SimpleDateFormat time = new SimpleDateFormat("yyyy-MM-dd:HH:mm:ss"); // private static Object lock1 = new Object(); private Object[] columnNames = { "用户名", "工作组","主机名","优先级", "IP地址", "port","" }; private String myName = ""; private UDP udpService; private static SendWindow sendWindow; int add =0; int count=0,flag=0; JFrame frame; File f; File file; JButton reFresh; JButton send; JButton file_btn; JButton open_file; JLabel userOnline; JLabel userCount; JCheckBox packaging; JCheckBox lock; JTable table; JTextArea inputArea; JScrollPane scrollPaneTable; JScrollPane scrollPaneFile; JSplitPane jSplitPane; JPanel panelSouth; JPanel panelSouthNorth; JPanel panelSouthSouth; JPanel panelNorth; JPanel panelNorthEast; private JFileChooser filechooser; private AddFileWindow addFileWindow; String filename = "",filePath = "",filepath=""; long fileSize = 0; int d = 0,port; public Vector fileVector = new Vector(); private void createWindow() { //分割容器 jSplitPane=new JSplitPane();//创建一个分割容器类 jSplitPane.setOrientation(JSplitPane.VERTICAL_SPLIT);//设置分割线方向 jSplitPane.setDividerSize(5); jSplitPane.setDividerLocation(50);//设置分割线位于中央 //上半部分整体布局 panelNorth = new JPanel(new BorderLayout()); panelNorthEast = new JPanel(new BorderLayout()); panelNorth.add(panelNorthEast,BorderLayout.EAST); jSplitPane.setTopComponent(panelNorth); //下半部分整体布局 panelSouth = new JPanel(new BorderLayout()); panelSouthNorth = new JPanel(); panelSouthSouth = new JPanel(); inputArea = new JTextArea(); scrollPaneFile = new JScrollPane(inputArea); scrollPaneFile.setPreferredSize(new Dimension(500, 150)); scrollPaneFile.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS); file_btn = new JButton(); // panelSouthNorth.add(fileName); file_btn.setVisible(false); FlowLayout flowLayout2 = new FlowLayout(FlowLayout.CENTER , 10 , 10); panelSouthSouth.setLayout(flowLayout2); panelSouth.add(file_btn,BorderLayout.NORTH); panelSouth.add(scrollPaneFile,BorderLayout.CENTER); panelSouth.add(panelSouthSouth,BorderLayout.SOUTH); jSplitPane.setBottomComponent(panelSouth); DefaultTableModel tableModel = new DefaultTableModel(null, columnNames); table = new JTable(tableModel){ private static final long serialVersionUID = 1L; @Override public boolean isCellEditable(int row, int column) { return false; } }; scrollPaneTable = new JScrollPane(); scrollPaneTable.setPreferredSize(new Dimension(500, 150)); //scrollPaneTable.setPreferredSize(panelNorth.getPreferredSize()); scrollPaneTable.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS); //scrollPane.setBounds(new Rectangle(76, 35, 257, 193)); //table.setFillsViewportHeight(true); //panelNorth.add(table.getTableHeader(), BorderLayout.PAGE_START); panelNorth.add(scrollPaneTable,BorderLayout.WEST); // JScrollPane tableScroll = new JScrollPane(); JTableHeader header = table.getTableHeader(); header.setBounds(0, 0, 400, 20); table.setBounds(0, 20, 400, 180); DefaultTableColumnModel columnModel = (DefaultTableColumnModel) table.getColumnModel(); columnModel.removeColumn(columnModel.getColumn(6)); scrollPaneTable.setViewportView(header); scrollPaneTable.setViewportView(table); scrollPaneTable.setBounds(0, 0, 400, 200); scrollPaneTable.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED); scrollPaneTable.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED); //scrollPaneTable = new JScrollPane(table); //scrollPaneTable.setPreferredSize(new Dimension(500, 150)); //scrollPaneTable.setPreferredSize(panelNorth.getPreferredSize()); //scrollPaneTable.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS); //scrollPane.setBounds(new Rectangle(76, 35, 257, 193)); //table.setFillsViewportHeight(true); //panelNorth.add(table.getTableHeader(), BorderLayout.PAGE_START); panelNorth.add(scrollPaneTable,BorderLayout.WEST); //上半部分标签和按钮 userOnline = new JLabel("在线用户",JLabel.CENTER); userCount = new JLabel("0",JLabel.CENTER); reFresh = new JButton("刷新(R)"); panelNorthEast.add(userOnline,BorderLayout.NORTH); panelNorthEast.add(userCount,BorderLayout.CENTER); panelNorthEast.add(reFresh,BorderLayout.SOUTH); //下半部分拖拽 DropTargetAdapter kgd=new DropTargetAdapter() { @Override public void drop(DropTargetDropEvent dtde) { try { Transferable tf=dtde.getTransferable(); if(tf.isDataFlavorSupported(DataFlavor.javaFileListFlavor)) { dtde.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE); List lt=(List)tf.getTransferData(DataFlavor.javaFileListFlavor); Iterator itor=lt.iterator(); while(itor.hasNext()) { f=(File)itor.next(); filename = f.getName(); fileSize = f.length(); filePath = f.getPath(); file_btn.setText(f.getName()); // fileName.setText(f.getPath()); //fileName.setText(f.getPath().substring(filePath.lastIndexOf("\\") + 1)); file_btn.setVisible(true); fileVector.add(f); add = 0; // flag+=1; //frame.removeAll(); // frame.repaint(); if(fileSize>0) { open_file.setEnabled(false); } } dtde.dropComplete(true); } else { dtde.rejectDrop(); } } catch(Exception e) { e.printStackTrace(); } } }; new DropTarget(inputArea,DnDConstants.ACTION_COPY_OR_MOVE,kgd); file_btn.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { addFileWindow = AddFileWindow.createWindow(getInstance()); addFileWindow.frame.setVisible(true); System.out.println("file_btn:"+f.getName()+f.length()+f.getPath()); addFileWindow.showFile(f.getName(),f.length(),f.getPath()); } }); //下半部分按钮和复选按钮 open_file = new JButton("添加文件"); send = new JButton("发送(S)"); packaging = new JCheckBox("封装(E)"); packaging.setSelected(true); lock = new JCheckBox("上锁(K)"); panelSouthSouth.add(open_file); panelSouthSouth.add(send); panelSouthSouth.add(packaging); panelSouthSouth.add(lock); open_file.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { filechooser = new JFileChooser(); filechooser.setFileSelectionMode(JFileChooser.FILES_ONLY); int option = filechooser.showDialog(null, "选择文件"); if (option == 0) { file = filechooser.getSelectedFile(); filePath = file.getPath(); file_btn.setText(file.getName()); file_btn.setVisible(true); add = 0; } } }); packaging.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if(packaging.isSelected()==false) { lock.setSelected(false); lock.setEnabled(false); } } }); //整个布局 frame = new JFrame("FastSend"); frame.setSize(595, 420); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setVisible(true); frame.setResizable(true); frame.setContentPane(jSplitPane); jSplitPane.setDividerLocation(0.5); //frame.pack(); frame.addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent event) { try { udpService.broadcast("offline#"); } catch (IOException e) { e.printStackTrace(); } } }); reFresh.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { frame.repaint(); } }); send.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { String msg = inputArea.getText(); if(add==1) { filepath = ""; } else { filepath = filePath; } System.out.println("1111filepath:"+filepath); if ((msg != null && msg.length() > 0) || (filepath != null && filepath.length() > 0)) { List<Map<String, String>> selected = getSelected(); if (selected == null) { JOptionPane.showMessageDialog(null, "请选择发送对象!", "注意", JOptionPane.INFORMATION_MESSAGE); return; } for (Map<String, String> map : selected) { String addr = map.get("addr"); int port = Integer.parseInt(map.get("port")); try { StringBuffer sb = new StringBuffer("msg#"); sb.append(myName); msg = (msg != null && msg.length() > 0) ? msg : "null"; sb.append("#" + msg.replaceAll("#", "*")); filepath = (filepath != null && filepath.length() > 0) ? filepath : "null"; sb.append("#" + filepath); //if(addFileWindow.) udpService.send(addr, port, sb.toString()); Vector sendList = new Vector( ); sendList.add(fileVector); int[] selectRows = table.getSelectedRows(); InetAddress sendAddress; DefaultTableModel model = (DefaultTableModel) table.getModel(); // for (int i = 0; i < selectRows.length; i++) { // String addr = model.getValueAt(selectRows[i], 3).toString(); sendAddress=InetAddress.getByName( ( String ) model.getValueAt (selectRows[0] ,3 ) ); Thread clientThread=new Thread(new Client( sendList ,sendAddress)); clientThread.setPriority(6); clientThread.start(); // } } catch (IOException e1) { e1.printStackTrace(); } } inputArea.setText(null); file_btn.setVisible(false); file_btn.setText(""); sendWindow.setVisible(false); //filepath = ""; filename = ""; fileSize = 0; filePath = ""; d= 1; System.out.println("哈哈"+filepath); } else { System.out.println("wode.."); JOptionPane.showMessageDialog(null, "请输入内容或选择文件!", "注意", JOptionPane.INFORMATION_MESSAGE); } } }); } private void addRow(String userName,String hostGroup,String hostName,String Priority,String hostAddr, int hostPort) { DefaultTableModel model = (DefaultTableModel) table.getModel(); model.addRow(new Object[] { userName,hostGroup,hostName, Priority,hostAddr, hostPort }); } private void rmRow(String addr) { DefaultTableModel model = (DefaultTableModel) table.getModel(); for (int i = 0, j = table.getRowCount(); i < j; i++) { String taddr = model.getValueAt(i, 2).toString(); if (taddr.equals(addr)) { model.removeRow(i); break; } } } private List<Map<String, String>> getSelected() { int[] selectRows = table.getSelectedRows(); if (selectRows.length == 0) { return null; } List<Map<String, String>> selected = new ArrayList<Map<String, String>>(); DefaultTableModel model = (DefaultTableModel) table.getModel(); for (int i = 0; i < selectRows.length; i++) { String addr = model.getValueAt(selectRows[i], 3).toString(); port = Integer.parseInt(model.getValueAt(selectRows[i], 5).toString()); Map<String, String> map = new HashMap<String, String>(); map.put("addr", addr); map.put("port", port + ""); selected.add(map); } return selected; } public void setInpuArea(String str) { this.inputArea.setText(str); } public void setVisible(boolean b) { frame.setVisible(b); } private SendWindow() throws IOException { this.createWindow(); myName = System.getProperty("user.name"); udpService = new UDP(); ReceiveThread thread = new ReceiveThread(); thread.start(); udpService.broadcast("online#" + myName); count++; userCount.setText(count+""); frame.repaint(); // TCP.init(); } public static SendWindow getInstance() { // synchronized (lock1) { if (sendWindow == null) { try { sendWindow = new SendWindow(); } catch (IOException e) { e.printStackTrace(); } } return sendWindow; // } } class ReceiveThread extends Thread { @Override public void run() { try { while (true) { Map<String, String> recMap = udpService.receive(); if (recMap != null && recMap.size() > 0) { handlData(recMap); } } } catch (IOException e) { e.printStackTrace(); } } void handlData(Map<String, String> recMap) throws IOException { String data = recMap.get("data").trim(); String hostName = recMap.get("hostName"); String hostGroup = ""; String hostAddr = recMap.get("hostAddr"); String Priority = ""; int hostPort = Integer.parseInt(recMap.get("hostPort")); String[] dataArr = data.split("#"); if (dataArr[0].equals("online")) {// 收到上线消息后回复发消息给我的人 String userName = dataArr[1]; addRow(userName,hostGroup,hostName, Priority,hostAddr, hostPort); udpService.send(hostAddr, hostPort, "reply#" + dataArr[1]); return; } if (dataArr[0].equals("reply")) {// 更新在线table if(!hostAddr.equals(InetAddress.getLocalHost().getHostAddress())){ String userName = dataArr[1]; addRow(userName,hostGroup,hostName, Priority,hostAddr, hostPort); count++; userCount.setText(count+""); frame.repaint(); } return; } if (dataArr[0].equals("offline")) {// 下线消息,更新table rmRow(hostAddr); count--; userCount.setText(count+""); frame.repaint(); return; } if (dataArr[0].equals("msg")) {// 接收文本消息 ReceiveWindow receiveWindow = ReceiveWindow.createWindow(getInstance()); String msg = dataArr[2].equals("null") ? "":dataArr[2]; String file = dataArr[3].equals("null") ? "":dataArr[3]; System.out.println("hhfilename"+file); receiveWindow.showMsg(dataArr[1] + "/" + hostName, msg, file, hostAddr); //addFileWindow.showFile( filename,fileSize,filePath); return; } } } public static void main(String[] args) throws IOException { SendWindow sendWindow = SendWindow.getInstance(); } } 这是接收客户端,是端口选择的问题吗,我要怎么改呢T T package com.fastSendFile; import java.awt.GridLayout; import java.util.*; import java.net.*; import java.io.*; import javax.swing.*; public class Client implements Runnable { private Vector Vname=new Vector(); private InetAddress address; private Vector sendDir = new Vector(); private Vector fileVector = new Vector(); private long totalSize; private long fileSize; private String fileName; private long receivedSize; private long skipSize; SendWindow sendWindow; Client( Vector file , InetAddress address) { fileVector.addAll ( file ) ; this.address = address; } public void getFiles(File file,String lastDir ,String localPath) { if(file.isFile()) { totalSize += file.length(); sendDir.add (localPath); Vname.add(new String(lastDir + "/"+file.getName())); } else if(file.isDirectory()) { lastDir = lastDir + "/" + file.getName(); String strs[] = file.list(); for(int i = 0 ;i < strs.length; i ++) { File newfile = new File( file.getAbsolutePath() + "/" + strs[i] ); getFiles( newfile , lastDir , localPath ); } } } public void run() { totalSize = 0; String send = ""; try { byte[] buffer = new byte[1024]; Socket sendSocket = new Socket(address, 20); DataInputStream in = new DataInputStream(sendSocket.getInputStream()); BufferedOutputStream outb = new BufferedOutputStream(sendSocket.getOutputStream(),512); DataOutputStream out = new DataOutputStream(outb); ObjectOutputStream oout = new ObjectOutputStream (out); oout.writeObject ( fileVector ); oout.flush (); ObjectInputStream oin = new ObjectInputStream ( in ); Vector accVector = (Vector) oin.readObject (); if ( sendWindow.d ==1) JOptionPane.showMessageDialog(null, "消息已发送","提示",JOptionPane.DEFAULT_OPTION); for (int i = 0 ; i < accVector .size (); i ++) { File temp = (File) accVector.get ( i ); send += " " + temp.getName (); getFiles( temp ,"",temp.getParent ()); } //receive file out.writeLong(totalSize); out.flush(); int rSize; File tempFile; String tempString; long count ; JFrame frame = new JFrame(); frame.setTitle("正在发送文件"); JLabel lable1 = new JLabel(); JLabel lable2 = new JLabel(); JLabel lable3 = new JLabel(); frame.add( lable1,"North" ); frame.add( lable3,"South" ); receivedSize = 0; JProgressBar bar = new JProgressBar ( 0 , (int)(totalSize/1024)); JProgressBar bar1 = new JProgressBar (); bar.setForeground(new java.awt.Color(102, 255, 102)); bar.setBorder(javax.swing.BorderFactory.createTitledBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(204, 204, 204)), "\u603b\u8fdb\u5ea6", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Dialog", 0, 13), new java.awt.Color(0, 0, 255))); bar.setDoubleBuffered(true); bar.setStringPainted ( true ) ; bar1.setSize (320,20); bar.setSize (320,20); bar1.setForeground(new java.awt.Color(102, 255, 102)); bar1.setBorder(javax.swing.BorderFactory.createTitledBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(204, 204, 204)), "当前进度", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Dialog", 0, 13), new java.awt.Color(0, 0, 255))); bar1.setDoubleBuffered(true); bar1.setStringPainted ( true ); JPanel jp = new JPanel(); jp.setLayout ( new GridLayout( 3 , 1 )); // jp.add ( new JLabel ("总进度: ")); jp.add ( bar ); // jp.add ( new JLabel( "当前进度: " )); jp.add ( bar1 ); jp.add ( lable2 ); frame.add ( jp ); String Lmessage1 = "总共要发送: "+String.valueOf( totalSize / 1024) + " KB"; String Lmessage2 = "速度: 0"; lable1.setText( Lmessage1 ); lable2.setText( Lmessage2 ); lable3.setText ( "共" + Vname.size () + "个文件,已完成" + 0 + "个"); RandomAccessFile inFile; frame.setBounds( 250 , 200 , 400 , 200); frame.setResizable ( false ); frame.setVisible(true); long baseTime = new Date().getTime(); for(int i = 0;i < Vname.size();i++) { count = 0; lable3.setText ( "共" + Vname.size () + "个文件,已完成" + i + "个"); bar1.setMinimum ( 0 ); tempString = ( String ) Vname.get(i); tempFile = new File( sendDir.get(i) + tempString); fileSize = tempFile.length(); jp.setToolTipText ( "正发送:" + tempString.substring ( 1 ) ); out.writeLong(fileSize); int locate = new Random().nextInt ( 1000 ); byte [] fileRandom = new byte [10]; if ( tempFile.length () < 1024 ) locate = -1 ; else fileRandom = getFile( locate,tempFile ); out.writeInt ( locate ); out.write ( fileRandom ); frame.setTitle ( "正发送文件:" + tempString.substring ( 1 ) ); bar1.setMaximum ( ( int )fileSize / 1024 ); bar1.setValue ( 0 ); byte data2[] = tempString.getBytes( "UTF-8" ); out.write(data2); out.flush(); skipSize = in.readLong(); rSize = in.read(buffer); String reBack = new String(buffer,0,rSize,"UTF-8"); if("S".equals(reBack)) { receivedSize += fileSize; count = fileSize; bar.setValue ( (int) receivedSize / 1024); bar1.setValue ((int) count / 1024); continue; } else { if("C".equals(reBack)) { receivedSize += skipSize; count = skipSize; bar.setValue ( ( int )receivedSize / 1024 ); bar1.setValue ( ( int )count /1024 ); inFile = new RandomAccessFile(tempFile, "r"); inFile.seek( skipSize ); } else { inFile=new RandomAccessFile(tempFile, "r"); } while((rSize = inFile.read(buffer)) != -1) { receivedSize += rSize; count += rSize; bar.setValue ( ( int )receivedSize / 1024 ); bar1.setValue ( ( int )count / 1024 ); lable2.setText("速度: "+ String.valueOf(receivedSize * 1000 / (new Date().getTime() - baseTime + 1) / 1024 )+" KB/s"); outb.write( buffer, 0 ,rSize ); } outb.flush(); inFile.close(); } } fileSize = -1; out.writeLong(fileSize); out.writeInt ( -1 ); out.write( new byte [10]); byte data3[] = "#发送完毕#".getBytes("UTF-8"); out.write(data3); out.flush(); frame.setVisible(false); JOptionPane.showMessageDialog(null, "发送完成!","提示", JOptionPane.DEFAULT_OPTION); in.close(); out.close(); sendSocket.close(); } catch(Exception e) { JOptionPane.showMessageDialog(null, "发送文件出错l:"+e,"错误", JOptionPane.ERROR_MESSAGE); } } public static byte [] getFile( int n , File file) { byte [] b = new byte [10]; try { RandomAccessFile rf = new RandomAccessFile(file,"r"); rf.seek ( n ); rf.read ( b, 0 ,b.length); rf.close (); } catch (Exception e) { } return b; } }

为什么,字符串数组不能直接作为参数传递,需要定义变量进行传递?

![图片说明](https://img-ask.csdn.net/upload/201903/02/1551509227_48285.png) 为什么,字符串数组不能直接作为参数传递,需要定义变量后以变量的形式进行传递?

Springmvc上传文件限制大小,异常处理返回报错信息后,eclipse控制台还报错

**1、web.xml配置:** ``` <?xml version="1.0" encoding="UTF-8"?> <web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"> <!-- 注册主控制器DispatcherServlet --> <servlet> <servlet-name>DispatcherServlet</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <!-- 指定spring配置文件位置 --> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:applicationContext.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>DispatcherServlet</servlet-name> <url-pattern>*.from</url-pattern> </servlet-mapping> <!-- 指定读取所有文件的编码格式 --> <filter> <filter-name>encodingFilter</filter-name> <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class> <init-param> <param-name>encoding</param-name> <param-value>UTF-8</param-value> </init-param> </filter> <filter-mapping> <filter-name>encodingFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> </web-app> ``` **spring的applicationContext.xml配置:** ``` <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xmlns:jdbc="http://www.springframework.org/schema/jdbc" xmlns:jee="http://www.springframework.org/schema/jee" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:jpa="http://www.springframework.org/schema/data/jpa" xmlns:util="http://www.springframework.org/schema/util" xmlns:mvc="http://www.springframework.org/schema/mvc" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-3.2.xsd http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.2.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa-1.3.xsd http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.2.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd"> <!-- 定义自动扫描组件 --> <context:component-scan base-package="controller"></context:component-scan> <!-- 定义@RequestMapping映射的注解驱动 --> <mvc:annotation-driven></mvc:annotation-driven> <!-- 定义视图解析器 --> <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix"> <value>/WEB-INF/jsp/</value> </property> <property name="suffix"> <value>.jsp</value> </property> </bean> <!-- 注册spring web mvc中处理上传事件的组件CommonsMultipartResolver, 而具体怎样处理上传文件,则是由导入的包common-upload.jar和common-io.jar去处理--> <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <property name="maxUploadSize" value="10240"></property> <property name="resolveLazily" value="true"></property> </bean> </beans> ``` **java代码Controller处理:** ``` package controller; import java.io.File; import java.util.HashMap; import java.util.Map; import javax.servlet.http.HttpServletRequest; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.multipart.MaxUploadSizeExceededException; import org.springframework.web.multipart.MultipartFile; import org.springframework.web.servlet.ModelAndView; @Controller public class UploadController { // 访问upload.jsp页面 @RequestMapping("/toUpload") public String toUpload() { return "upload"; } @RequestMapping("/upload") public String upload(@RequestParam("file") MultipartFile file, HttpServletRequest request, ModelMap model) throws Exception { // 判断提交来的文件是否为空 if (file.isEmpty()) { // model.addAttribute("error", "上传文件不能为空"); // return "upload"; throw new RuntimeException("file is null"); } // 获取文件所要保存目录在服务器上所对应的实际路径 String path = request.getSession().getServletContext().getRealPath( "upload"); System.out.println(path); // 组成拥有真实路径的一个完整的地址字符串 String fileUrl = path + "\\" + file.getOriginalFilename(); // 封装上传文件名称到model对象中 model.addAttribute("fileName", file.getOriginalFilename()); // 根据这个完整地址字符串,生成提交文件所要保存到的目标文件或目录的对象 File targetFile = new File(fileUrl); // 判断目标文件或目录的对象是否已经存在 if (!targetFile.exists()) { targetFile.mkdirs(); } // 传送文件到目标对象 file.transferTo(targetFile); System.out.println("已上传文件:" + file); return "ok"; } @ExceptionHandler public ModelAndView doException(Exception e,HttpServletRequest request) throws Exception { Map<String,Object> map = new HashMap<String,Object>(); if (e instanceof MaxUploadSizeExceededException) { long maxSize = ((MaxUploadSizeExceededException) e) .getMaxUploadSize(); map.put("error", "上传文件太大,不能超过" + maxSize / 1024 + "k"); }else if(e instanceof RuntimeException){ map.put("error", "未选中文件"); }else{ map.put("error", "上传失败"); } return new ModelAndView("upload",map); } } ``` **上传文件页面upload.jsp:** ``` <%@ page pageEncoding="UTF-8" contentType="text/html;charset=UTF-8"%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <title>上传页面</title> </head> <body> <form action="upload.from" method="post" enctype="multipart/form-data"> <input type="file" name="file"/> <input type="submit" value="上传"/><font color="red">${error}</font> </form> </body> </html> ``` **上传成功页面ok.jsp:** ``` <%@ page pageEncoding="UTF-8" contentType="text/html;charset=UTF-8"%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <title>ok.jsp</title> </head> <body> <h1>上传成功</h1> <a href="upload/${fileName}">${fileName}</a> </body> </html> ``` **eclipse控制台报错信息如下:** ``` 五月 01, 2015 10:27:01 下午 org.springframework.web.multipart.commons.CommonsMultipartResolver cleanupMultipart 警告: Failed to perform multipart cleanup for servlet request org.springframework.web.multipart.MaxUploadSizeExceededException: Maximum upload size of 10240 bytes exceeded; nested exception is org.apache.commons.fileupload.FileUploadBase$SizeLimitExceededException: the request was rejected because its size (19243) exceeds the configured maximum (10240) at org.springframework.web.multipart.commons.CommonsMultipartResolver.parseRequest(CommonsMultipartResolver.java:160) at org.springframework.web.multipart.commons.CommonsMultipartResolver$1.initializeMultipart(CommonsMultipartResolver.java:131) at org.springframework.web.multipart.support.AbstractMultipartHttpServletRequest.getMultipartFiles(AbstractMultipartHttpServletRequest.java:119) at org.springframework.web.multipart.support.AbstractMultipartHttpServletRequest.getMultiFileMap(AbstractMultipartHttpServletRequest.java:99) at org.springframework.web.multipart.commons.CommonsMultipartResolver.cleanupMultipart(CommonsMultipartResolver.java:188) at org.springframework.web.servlet.DispatcherServlet.cleanupMultipart(DispatcherServlet.java:1062) at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:955) at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:856) at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:953) at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:855) at javax.servlet.http.HttpServlet.service(HttpServlet.java:650) at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:829) at javax.servlet.http.HttpServlet.service(HttpServlet.java:731) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208) at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208) at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:88) at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208) at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:220) at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:122) at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:505) at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:170) at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103) at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:950) at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116) at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:423) at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1079) at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:620) at org.apache.tomcat.util.net.AprEndpoint$SocketProcessor.doRun(AprEndpoint.java:2476) at org.apache.tomcat.util.net.AprEndpoint$SocketProcessor.run(AprEndpoint.java:2465) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615) at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) at java.lang.Thread.run(Thread.java:745) Caused by: org.apache.commons.fileupload.FileUploadBase$SizeLimitExceededException: the request was rejected because its size (19243) exceeds the configured maximum (10240) at org.apache.commons.fileupload.FileUploadBase$FileItemIteratorImpl.<init>(FileUploadBase.java:914) at org.apache.commons.fileupload.FileUploadBase.getItemIterator(FileUploadBase.java:331) at org.apache.commons.fileupload.FileUploadBase.parseRequest(FileUploadBase.java:349) at org.apache.commons.fileupload.servlet.ServletFileUpload.parseRequest(ServletFileUpload.java:126) at org.springframework.web.multipart.commons.CommonsMultipartResolver.parseRequest(CommonsMultipartResolver.java:156) ... 37 more ``` 上传文件超过限制大小,异常处理后页面返回了提示信息“上传文件太大,不能超过10k”,但是为啥eclipse的控制台还是有报错呢?

objectinputstream readobject 为何只能读取第一次写入的值

public class TransEntity implements Serializable//传输信息实体封装类 { private static final long serialVersionUID = 1L; private String operaType;//用户操作类型;如发送文本消息,发送语音消息,发送音频消息 private String responseTags;//网络响应状态;如“登录成功”、“登录失败”、“注册成功”、“注册失败” private String requestTags;//网络请求标记;请求发送文本消息,语音消息,音频消息 private User sender;//发送方; private User receiver;//接收方; private ArrayList<HashMap<String,Object>> buddylist;//好友列表信息; private String time;//系统时间; private ArrayList<HashMap<String,String>> inputGeneralMsgList;//通用信息 private HashMap<String,Object> outGeneralMsgMap; private String path; public String getUserOperaType() { return operaType; } public void setUserOperaType(String operaType) { this.operaType = operaType; } public String getResponseTags() { return responseTags; } public String setResponseTags(String responseTags) { return this.responseTags = responseTags; } public void setRequestTags(String requestTags) { this.requestTags = requestTags; } public String getRequestTags() { return requestTags; } public User getSender() { return sender; } public void setSender(User sender) { this.sender = sender; } public User getReceiver() { return receiver; } public void setReceiver(User receiver) { this.receiver = receiver; } public ArrayList<HashMap<String,Object>> getList() { return buddylist; } public void setList(ArrayList<HashMap<String,Object>> buddylist) { this.buddylist = buddylist; } public String getImagePath() { return path; } public void setImagePath(String path) { this.path = path; } public void setGeneralMessagefrom(ArrayList<HashMap<String,String>> inputGeneralMsgList) { this.inputGeneralMsgList = inputGeneralMsgList; } public ArrayList<HashMap<String,String>> getGeneralMessagefrom() { return inputGeneralMsgList; } public void setGeneralMessageto(HashMap<String,Object> outGeneralMsgMap) { this.outGeneralMsgMap = outGeneralMsgMap; } public HashMap<String,Object> getGeneralMessageto() { return outGeneralMsgMap; } public void setSysTime(String time) { this.time = SysTime.getDateTime(); } public String getSysTime() { return time; } } 服务端核心代码 public class ServerThread extends Thread { private static ObjectInputStream ois = null; private static ObjectOutputStream oos = null; private ArrayList<HashMap<String,Object>> list = null; private ArrayList<HashMap<String,String>> outgeneralMsgList = null; private Socket socket = null; private TransEntity trans = null; private boolean FLAGS_IsFirstLogin = true; private boolean FLAGS_LoginSucess = false; private boolean FLAGS_RegisterSucess = false; private boolean FLAGS_OnLine = false; private User user = null; private User receiver = null; private Timer timer = new Timer(); public ServerThread(Socket socket) { this.socket = socket; try { oos = new ObjectOutputStream(socket.getOutputStream()); ois = new ObjectInputStream(socket.getInputStream()); } catch (IOException e) { e.printStackTrace(); } } public void run() { try { while(true) { if(socket.isClosed() == false && socket.isConnected() == true) { try { if(ois!=null) { trans = (TransEntity) ois.readObject(); } } catch(java.net.SocketException e) { System.out.println("客户端已经关闭。。。。。。。"); break; } catch(ClassNotFoundException e) { System.out.println("--------空指针异常---------"); } catch(java.io.EOFException e) { System.out.println("客户端已经关闭。。。。。。。"); } } if(trans!=null) { user = trans.getSender(); receiver = trans.getReceiver(); if(trans.getUserOperaType()!=null) { System.out.println("----------trans.getUserOperaType() :------------"+(trans.getUserOperaType())); if(FLAGS_IsFirstLogin == true&&(UserOperaType.LOGIN.equals(trans.getUserOperaType()))) { //首次登录,一般情形下的客户端发过来的登录操作请求做处理,非掉线后的自动登录; System.out.println("--------server---socket :------"+(socket)); FLAGS_LoginSucess = setLogin(); } if(FLAGS_LoginSucess) { FLAGS_IsFirstLogin = false; System.out.println("----------trans.getUserOperaType() :------------"+(trans.getUserOperaType())); ......为何此次只能输出第一次读入的数据 if(UserOperaType.SEND_MESSAGE.equals(trans.getUserOperaType())) { System.out.println("-------UserOperaType.SEND_MESSAGE ---------"); System.out.println(trans.getGeneralMessageto().get("outMsg").toString()); if(trans.getGeneralMessageto()!=null)//若getGeneralMessageto()返回值不为空,则可以向数据库写入信息; { System.out.println("-------服务端:---发送方 写入普通信息到数据库,如文字消息;-----------"); SysCtlVar.dbBasicOperation.writeGeneralMessage(trans);// 发送方 写入普通信息到数据库,如文字消息; //trans.setGeneralMessageto(null); } trans.setUserOperaType(null); } oos.writeObject(trans); oos.flush(); } } } } } catch (Exception e) { e.printStackTrace(); } finally { } } } 客户端核心代码 while(SysCtlVar.FlAGS_LoginSuccess) { // System.out.println("--------------while SysCtlVar.FlAGS_LoginSuccess -------------"); try { try { SysCtlVar.trans = (TransEntity)SysCtlVar.ois.readObject(); if(SysCtlVar.inputGeneralMsgList!=null) synchronized(SysCtlVar.inputGeneralMsgList) { SysCtlVar.inputGeneralMsgList = SysCtlVar.trans.getGeneralMessagefrom(); SysCtlVar.inputGeneralMsgList.notify(); } synchronized(SysCtlVar.outGeneralMsgMap) { try { System.out.println("------- SysCtlVar.outGeneralMsgMap.wait----------"); SysCtlVar.outGeneralMsgMap.wait(); //等待直到有输入的时候,才把消息发送出去 System.out.println("---------------客户端: 正在发送消息。。。。。。------------------"); System.out.println("------- SysCtlVar.outGeneralMsgMap:----------"+(SysCtlVar.outGeneralMsgMap.get("outMsg").toString())); SysCtlVar.trans.setUserOperaType(UserOperaType.SEND_MESSAGE); SysCtlVar.trans.setGeneralMessageto(SysCtlVar.outGeneralMsgMap); System.out.println("------- SysCtlVar.trans.getGeneralMessageto():----------"+(SysCtlVar.trans.getGeneralMessageto().get("outMsg").toString())); try { SysCtlVar.oos.writeObject(SysCtlVar.trans); SysCtlVar.oos.flush(); } catch (IOException e) { e.printStackTrace(); } } catch (InterruptedException e) { e.printStackTrace(); } } } catch (ClassNotFoundException e) { e.printStackTrace(); } } catch (StreamCorruptedException e1) { e1.printStackTrace(); } catch (IOException e1) { e1.printStackTrace(); } } } 客户端 数据输入部分 /** 调试过程中,你将看到客户端输入的消息为h(第一条消息),www(第二条消息),a(第三条消息) 但是服务端只有第二条消息的值; */ //------------------发送消息 ---------- //客户端当前会话任务中,选中的消息接收者; new Thread() { public void run() { synchronized(SysCtlVar.outGeneralMsgMap) { System.out.println("------- 客户端:正在输入要发送的消息----------"); SysCtlVar.outGeneralMsgMap.clear(); SysCtlVar.outGeneralMsgMap.put("outMsg",outMsg); SysCtlVar.outGeneralMsgMap.put("msgRecver", selectedAccount); SysCtlVar.outGeneralMsgMap.put("dateTime",SysTime.getDateTime().toString()); SysCtlVar.outGeneralMsgMap.notify(); //输入完毕,通知发送任务执行 } } }.start(); 调试信息(服务器端) 服务器已启动,正在监听1345端口 ----------trans.getUserOperaType() :------------0 --------server---socket :------Socket[addr=/127.0.0.1,port=38516,localport=1345] ------- list!=null : ---------true [qq]上线了! ----------qq---------- ----------trans.getUserOperaType() :------------0 ----------trans.getUserOperaType() :------------6 ----------trans.getUserOperaType() :------------6 -------------UserOperaType.GET_AVATARS------------6 我想从服务器获取头像 ----------trans.getUserOperaType() :------------7 ----------trans.getUserOperaType() :------------7 -------UserOperaType.SEND_MESSAGE --------- www -------服务端:---发送方 写入普通信息到数据库,如文字消息;----------- insert into chat(sender,recver,message,sendtime) values('qq','在水一方','www','2015-04-24 16:15:13') ----------trans.getUserOperaType() :------------7 ----------trans.getUserOperaType() :------------7 -------UserOperaType.SEND_MESSAGE --------- www -------服务端:---发送方 写入普通信息到数据库,如文字消息;----------- insert into chat(sender,recver,message,sendtime) values('qq','在水一方','www','2015-04-24 16:15:13') ----------trans.getUserOperaType() :------------7 ----------trans.getUserOperaType() :------------7 -------UserOperaType.SEND_MESSAGE --------- www -------服务端:---发送方 写入普通信息到数据库,如文字消息;----------- insert into chat(sender,recver,message,sendtime) values('qq','在水一方','www','2015-04-24 16:15:13') ----------trans.getUserOperaType() :------------7 ----------trans.getUserOperaType() :------------7 -------UserOperaType.SEND_MESSAGE --------- www -------服务端:---发送方 写入普通信息到数据库,如文字消息;----------- insert into chat(sender,recver,message,sendtime) values('qq','在水一方','www','2015-04-24 16:15:13') ---------------问题补充--------------- 单步调试,客户端的输出流正确发送了每一次的客户端输入数据(36分钟前)删除 对于单步调试追踪的结果:客户端每一次发送的trans(它是TransEntity的实例,被序列化的消息实体对象)都是正确的(即,与客户端输入值相同)。但是服务端有ObjectInputStream读入的trans(它也是TransEntity的实例,被序列化的消息实体对象)却没有改变始终是第一次的值

get请求,参数拼接,时间字符串拼接报错,然后大佬们说的我好想不太清楚咋弄,就新添了请求方法,和调用

java.io.IOException: Server returned HTTP response code: 400 for URL: http://api.baidu.com/getsyncusers?code=02&date=2019-10-10 10:16:00.0 at sun.net.www.protocol.http.HttpURLConnection.getInputStream0(HttpURLConnection.java:1894) at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1492) at com.dunan.zzjg.util.ApiGateToken.getResponseContext(ApiGateToken.java:115) at com.dunan.zzjg.service.impl.SysUserServiceImpl.setSyncUsers(SysUserServiceImpl.java:82) at com.dunan.zzjg.controller.DAapiController.userDate(DAapiController.java:44) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:498) at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:190) at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:138) at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:104) at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:892) at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:797) at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87) at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1039) at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:942) at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1005) at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:897) at javax.servlet.http.HttpServlet.service(HttpServlet.java:634) at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:882) at javax.servlet.http.HttpServlet.service(HttpServlet.java:741) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) at com.alibaba.druid.support.http.WebStatFilter.doFilter(WebStatFilter.java:123) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) at org.springframework.boot.actuate.web.trace.servlet.HttpTraceFilter.doFilterInternal(HttpTraceFilter.java:90) at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:320) at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:127) at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.doFilter(FilterSecurityInterceptor.java:91) at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) at org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:119) at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) at org.springframework.security.web.session.SessionManagementFilter.doFilter(SessionManagementFilter.java:137) at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) at org.springframework.security.web.authentication.AnonymousAuthenticationFilter.doFilter(AnonymousAuthenticationFilter.java:111) at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) at org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter.doFilter(SecurityContextHolderAwareRequestFilter.java:170) at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) at org.springframework.security.web.savedrequest.RequestCacheAwareFilter.doFilter(RequestCacheAwareFilter.java:63) at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) at org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:116) at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) at org.springframework.web.filter.CorsFilter.doFilterInternal(CorsFilter.java:96) at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) at org.springframework.security.web.header.HeaderWriterFilter.doFilterInternal(HeaderWriterFilter.java:66) at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) at org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:105) at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) at org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter.doFilterInternal(WebAsyncManagerIntegrationFilter.java:56) at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) at org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:215) at org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:178) at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:357) at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:270) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:99) at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) at org.springframework.web.filter.FormContentFilter.doFilterInternal(FormContentFilter.java:92) at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) at org.springframework.web.filter.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.java:93) at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) at org.springframework.boot.actuate.metrics.web.servlet.WebMvcMetricsFilter.filterAndRecordMetrics(WebMvcMetricsFilter.java:117) at org.springframework.boot.actuate.metrics.web.servlet.WebMvcMetricsFilter.doFilterInternal(WebMvcMetricsFilter.java:106) at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:200) at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:200) at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96) at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:490) at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:139) at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92) at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:74) at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:343) at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:408) at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66) at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:836) at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1747) at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624) at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) at java.lang.Thread.run(Thread.java:748) /** * 根据请求地址及请求参数,获取服务器的相应信息 * * @param requestURL 请求地址 * @param requestParam 请求参数 * @param requestMethod "POST" or "GET" * @return */ public static String getResponseContext(String requestURL, String requestParam, String requestMethod,String token) { StringBuffer responseContext = new StringBuffer(); try { URL url = new URL(requestURL); // 此处的urlConnection对象实际上是根据URL的 URLConnection urlConn = url.openConnection(); urlConn.setConnectTimeout(30000); urlConn.setReadTimeout(30000); // 请求协议(此处是http)生成的URLConnection类 的子类HttpURLConnection,故此处最好将其转化 // 为HttpURLConnection类型的对象,以便用到 HttpURLConnection更多的API.如下: HttpURLConnection httpUrlConnection = (HttpURLConnection) urlConn; // 设置是否向httpUrlConnection输出,因为这个是post请求,参数要放在 // http正文内,因此需要设为true, 默认情况下是false; httpUrlConnection.setDoOutput(true); // 设置是否从httpUrlConnection读入,默认情况下是true; httpUrlConnection.setDoInput(true); // Post 请求不能使用缓存 httpUrlConnection.setUseCaches(false); // 设定传送的内容类型是可序列化的java对象 // (如果不设此项,在传送序列化对象时,当WEB服务默认的不是这种类型时可能抛java.io.EOFException) httpUrlConnection.setRequestProperty("Content-type","application/json"); // 设置 HttpURLConnection的字符编码 httpUrlConnection.setRequestProperty("Accept-Charset", "UTF-8"); if(StringUtils.isNotBlank(token)){ httpUrlConnection.setRequestProperty("Access-Token", token); } // 设定请求的方法为"POST",默认是GET httpUrlConnection.setRequestMethod(requestMethod); // 连接,从上述第2条中url.openConnection()至此的配置必须要在connect之前完成, // // 此处getOutputStream会隐含的进行connect(即:如同调用上面的connect()方法, // // 所以在开发中不调用上述的connect()也可以)。 if("POST".equals(requestMethod)){ OutputStream outStrm = httpUrlConnection.getOutputStream(); outStrm.write(requestParam.getBytes("UTF-8")); // // 刷新对象输出流,将任何字节都写入潜在的流中(些处为ObjectOutputStream) outStrm.flush(); // 关闭流对象。此时,不能再向对象输出流写入任何数据,先前写入的数据存在于内存缓冲区中, // 在调用下边的getInputStream()函数时才把准备好的http请求正式发送到服务器 outStrm.close(); } // 调用HttpURLConnection连接对象的getInputStream()函数, // 将内存缓冲区中封装好的完整的HTTP请求电文发送到服务端。 InputStream inStrm = httpUrlConnection.getInputStream(); // 读取文件流程 BufferedReader rd = new BufferedReader( new InputStreamReader(inStrm,"UTF-8")); // 采取行的方式进行读取 String tempLine = rd.readLine(); // 循环获取每一行数据 while (tempLine != null) { responseContext.append(tempLine); tempLine = rd.readLine(); } rd.close(); inStrm.close(); httpUrlConnection.disconnect(); httpUrlConnection = null; urlConn = null; url = null; } catch (Exception e) { e.printStackTrace(); } return responseContext.toString(); } /*获取上次更新的时间*/ TurnoverTime lastTime = timeMapper.selectTime(); String lastUpdateTime = lastTime.getLastUpdateTime(); System.out.println(lastUpdateTime); String url = "http://api.baidu.com/getsyncusers"; String param = "?code="+"02"+"&date="+lastUpdateTime; String requestMethod = "GET"; String token = ApiGateToken.getToken(); String responseContext = ApiGateToken.getResponseContext(url+param, param, requestMethod, token);

jsp内获取session里变量的值

var session_value = '<%=session.getAttribute("verificationCode")%>';在jsp页面内 把session_value输出,首次没有值,刷新页面得到首次回话的值

hibernate中的事务问题

package cn.itcast.hibernatetest; import org.hibernate.HibernateException; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.Transaction; import org.hibernate.cfg.Configuration; import org.junit.Test; import cn.itcast.entity.User; public class HibernateDemo { @Test public void testAdd() { //第一步 加载hibernate核心配置文件 //到src下面照到一个名词是hibernate.cfg.xml //在hibernate里面封装了一个对象 Configuration cfg=new Configuration(); cfg.configure(); //第二步,创建一个SessionFactory对象 //读取hibernate核心配置文件,创建sessionFactory //在过程中,根据映射关系,在配置数据库里面把表创建 SessionFactory sessionFactory = cfg.buildSessionFactory(); //第三步 使用SessionFactory创建session对象 //类似于连接 Session session = sessionFactory.openSession(); //第四步 开启事务 Transaction tx = session.beginTransaction(); //第五步 写具体逻辑crud操作 User user = new User(); user.setUsername("小王"); user.setPassword("250"); user.setAdress("日本"); //调用session的方法实现添加 session.save(user); //第六步 提交事务 tx.commit(); //第七步 关闭资源 session.close(); sessionFactory.close(); } } 代码tx.commit();报错,输入tx.的时候也没有提示commit()方法,为什么,错误提示好像是Transaction中没有commit方法? 错误提示如下: The type javax.persistence.EntityTransaction cannot be resolved. It is indirectly referenced from required .class files 有没有大神解答下,谢谢了

尝试写了一个 JDBC 操作 SQLServer 的工具类,但是好像有问题,求大神帮忙指正

java新人,尝试写了一个 JDBC 操作 SQLServer 的工具类,但是好像有问题,调用 insert 指令没问题,而 select 指令出现如下报错: com.microsoft.sqlserver.jdbc.SQLServerException: ')' 附近有语法错误。 at com.microsoft.sqlserver.jdbc.SQLServerException.makeFromDatabaseError(SQLServerException.java:216) at com.microsoft.sqlserver.jdbc.SQLServerStatement.getNextResult(SQLServerStatement.java:1515) at com.microsoft.sqlserver.jdbc.SQLServerStatement.doExecuteStatement(SQLServerStatement.java:792) at com.microsoft.sqlserver.jdbc.SQLServerStatement$StmtExecCmd.doExecute(SQLServerStatement.java:689) at com.microsoft.sqlserver.jdbc.TDSCommand.execute(IOBuffer.java:5696) at com.microsoft.sqlserver.jdbc.SQLServerConnection.executeCommand(SQLServerConnection.java:1715) at com.microsoft.sqlserver.jdbc.SQLServerStatement.executeCommand(SQLServerStatement.java:180) at com.microsoft.sqlserver.jdbc.SQLServerStatement.executeStatement(SQLServerStatement.java:155) at com.microsoft.sqlserver.jdbc.SQLServerStatement.executeQuery(SQLServerStatement.java:616) at com.javaee.servletxm.comm.MSSQLJDBC.select(MSSQLJDBC.java:160) at com.javaee.servletxm.comm.MSSQLJDBC.select(MSSQLJDBC.java:195) at com.javaee.servletxm.comm.MSSQLJDBC.selectFirstValue(MSSQLJDBC.java:172) at com.javaee.servletxm.comm.MSSQLJDBC.getPageNumber(MSSQLJDBC.java:221) at com.javaee.servletxm.comm.MSSQLJDBC.selectByFY(MSSQLJDBC.java:259) at com.javaee.servletxm.kqgl.KqManager.getAllKqxx(KqManager.java:38) at com.javaee.servletxm.kqgl.Kqwh.doGet(Kqwh.java:47) at javax.servlet.http.HttpServlet.service(HttpServlet.java:617) at javax.servlet.http.HttpServlet.service(HttpServlet.java:723) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206) at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233) at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191) at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:127) at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103) at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109) at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:293) at org.apache.coyote.http11.Http11AprProcessor.process(Http11AprProcessor.java:879) at org.apache.coyote.http11.Http11AprProtocol$Http11ConnectionHandler.process(Http11AprProtocol.java:617) at org.apache.tomcat.util.net.AprEndpoint$Worker.run(AprEndpoint.java:1760) at java.lang.Thread.run(Thread.java:724) 这是具体的代码,求大神帮忙指正 package com.javaee.servletxm.comm; /** * jdbc下 SQL Server 2005 数据库的封装类 */ import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.sql.CallableStatement; import java.sql.Connection; import java.sql.Date; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.ResultSetMetaData; import java.sql.SQLException; import java.sql.Statement; import java.sql.Timestamp; import java.text.SimpleDateFormat; import java.util.List; import java.util.Properties; public class MSSQLJDBC { // 配置文件名称 private String iniFileName = MSSQLJDBC.class.getClassLoader().getResource("/com/javaee/servletxm/comm").getPath()+ "mssql.properties"; // 连接数据库 private String driver = "com.microsoft.sqlserver.jdbc.SQLServerDriver"; private String url = "jdbc:sqlserver://localhost;DatabaseName=jdms"; private String user = "sa"; private String password = ""; // 定义连接属性 private Connection connect = null; // 与连接有关三个通道 private Statement stmt = null; private PreparedStatement pstmt = null; private CallableStatement cstmt = null; public static final String stmtType = "stmt"; public static final String pstmtType = "pstmt"; public static final String cstmtType = "cstmt"; // 定义参数类型的静态常量值 public static final String varCharType = "varchar"; public static final String intType = "int"; public static final String doubleType = "decimal"; public static final String dateType = "datetime"; public static final String timeType = "timestamp"; // 定义全局的结果集 private ResultSet rs = null; // 在构造方法中对属性进行初始化赋值操作 public MSSQLJDBC() { // 读取配置文件 readIni(); // 初始化连接 initConnect(); } // 可配置文件 .properties // 读取配置文件 private void readIni() { File file = new File(iniFileName); if (!file.exists()) { // 创建一个文件 try { file.createNewFile(); } catch (IOException e) { e.printStackTrace(); } } // 判断文件是否有值 if (file.length() == 0) {// 说明是一个空文件 // 初始化值 try { Properties p = new Properties(); p.put("driver", driver); p.put("url", url); p.put("user", user); p.put("password", password); FileOutputStream fos = new FileOutputStream(file); p.store(fos, "配置文件信息"); fos.close(); } catch (IOException e) { e.printStackTrace(); } } else {// 如果有值 // 将信息读取出来 try { FileInputStream fis = new FileInputStream(file); Properties p = new Properties(); p.load(fis); this.driver = p.getProperty("driver"); this.url = p.getProperty("url"); this.user = p.getProperty("user"); this.password = p.getProperty("password"); fis.close(); } catch (IOException e) { e.printStackTrace(); } } } // 建立连接 private void initConnect() { try { Class.forName(driver); this.connect = DriverManager.getConnection(url, user, password); this.connect.setAutoCommit(false);// 设置手动提交事务 this.stmt = connect.createStatement(); } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (SQLException e) { e.printStackTrace(); } } /*/ 从tomcat缓冲池获取连接 private void initConnectFromDataSource() { try { InitialContext ic = new InitialContext(); DataSource ds = (DataSource) ic.lookup("java:comp/env/jdbc/oracleds"); this.connect = ds.getConnection(); this.connect.setAutoCommit(false); this.stmt = connect.createStatement(); } catch (NamingException e) { e.printStackTrace(); } catch (SQLException e) { e.printStackTrace(); } }*/ // 需要调用者控制事务的两个方法 // 提交方法 private void commit() { try { this.connect.commit(); } catch (SQLException e) { e.printStackTrace(); } } // 回滚事务 private void rollBack() { try { this.connect.rollback(); } catch (SQLException e) { e.printStackTrace(); } } // 定义一组与操作有关的方法 // 使用普通通道执行的select public ResultSet select(String sql) { ResultSet prs = null; if (stmt != null) { try { prs = stmt.executeQuery(sql); } catch (SQLException e) { e.printStackTrace(); } } return prs; } // 根据传入的sql直接获取单一值 // 使用此方法的时候sql语句返回的单一的值 public String selectFirstValue(String sql, String type, List<String> csList) { String rstr = ""; rs = select(sql, type, csList);// 确定此结果集只有一条记录 if (rs != null) {// 说明结果集有值,且只有一条记录 try { ResultSetMetaData rsmd = rs.getMetaData(); if (rs.next()) { // 移动到第一条记录 String p_type = rsmd.getColumnTypeName(1); rstr = getResultSetValue(rs, 1, p_type); } } catch (SQLException e) { e.printStackTrace(); } } return rstr; } // 使用普通通道执行的select /** * sql 参数 type 使用通道的类型 stmt pstmt cstmt List<String> csList 预编通道执行的参数队列 * String 最少必须满足如下条件的字符串 数据类型 ,数据值 数据类型定义说明 字符串 数字(整数、小数) 日期(DATE、TIMESTAMP) */ public ResultSet select(String sql, String type, List<String> csList) { ResultSet prs = null; if (type.equals(stmtType)) {// 说明使用普通通道来执行 prs = select(sql); } else if (type.equals(pstmtType)) {// 说明使用预编译通道来执行 if (connect != null) { try { pstmt = connect.prepareStatement(sql); // 验证传入的参数和sql中的参数个数一致 setPrepareStatement(pstmt, csList);// 将参数设置进当前的预编译通道 prs = pstmt.executeQuery(); } catch (Exception e) { e.printStackTrace(); } } } return prs; } // 获取 总页数 public int getPageNumber(String sql, String type, List<String> csList, int pageSize) { // 处理总页数 int pageNumber = 0; // 第一步获取sql总记录数 String psql = "select count(*) from (" + sql + ")"; String result = selectFirstValue(psql, type, csList); int rows = 0; if (result != null && result.trim() != "") { rows = Integer.valueOf(result); } if (rows % pageSize == 0) { pageNumber = rows / pageSize; } else { pageNumber = rows / pageSize + 1; } return pageNumber; } /** * 自动添加分页查询方法 * * @param sql * 要执行的sql * @param type * 执行方式 * @param csList * 参数列表 * @param curPage * 当前页数 * @param pageSize * 每页记录数 默认为10 * @return */ public ResultSet selectByFY(String sql, String type, List<String> csList, int curPage, int pageSize) { ResultSet prs = null; // 处理 每页记录数 if (pageSize <= 0) { pageSize = 10;// 默认页面10条记录 } int pageNumber = getPageNumber(sql, type, csList, pageSize); // 处理当前页数 if (curPage < 0) { curPage = 1;// 默认第一页 } if (curPage > pageNumber) { curPage = pageNumber; } String psql = "select tmpaa.* from (select tmpa.*,(select (ROW_NUMBER() over (order by id))) as rn from (" + sql + ") tmpa where (select (ROW_NUMBER() over (order by id))) <= " + (curPage * pageSize) + ") tmpaa where tmpaa.rn >= " + ((curPage - 1) * pageSize + 1); prs = select(psql, type, csList); return prs; } // 将预编通道执行的参数队列按照指定规则设置进通道中 private void setPrepareStatement(PreparedStatement p, List<String> csList) throws Exception { if (csList != null && csList.size() > 0) { for (int i = 0; i < csList.size(); i++) { // 此处的str是数据类型 ,数据值 // 解析出数据类型和数据值 String[] s = csList.get(i).split(","); String sType = s[0]; String sData = s[1]; if (varCharType.equals(sType)) { p.setString(i + 1, sData); } else if (intType.equals(sType)) { p.setInt(i + 1, Integer.valueOf(sData)); } else if(doubleType.equals(sType)){ p.setDouble(i+1, Double.valueOf(sData)); } else if (dateType.equals(sType)) { SimpleDateFormat sdf = new SimpleDateFormat("yyyy-mm-dd"); java.util.Date d = sdf.parse(sData); p.setDate(i + 1, new Date(d.getTime())); } else if (timeType.equals(sType)) { SimpleDateFormat sdf = new SimpleDateFormat("yyyy-mm-dd"); java.util.Date d = sdf.parse(sData); p.setTimestamp(i + 1, new Timestamp(d.getTime())); } } } } // 定义一个执行insert update delete的方法 public int iudSql(String sql) { int ri = -1; if (stmt != null) { try { ri = stmt.executeUpdate(sql); commit(); } catch (SQLException e) { e.printStackTrace(); rollBack(); } } return ri; } public int iudSql(String sql, String type, List<String> csList) { int ri = -1; if (stmtType.equals(type)) { ri = iudSql(sql); } else if (pstmtType.equals(type)) { if (connect != null) { try { pstmt = connect.prepareStatement(sql); setPrepareStatement(pstmt, csList); ri = pstmt.executeUpdate(); commit(); } catch (Exception e) { e.printStackTrace(); rollBack(); } } } return ri; } /** * 编写一个通用的遍历ResultSet结果集的方法 */ public void iteratorResultSet(ResultSet rs) { try { if (rs != null) {// 说明有值 // ResultSetMetaData 此对象里封装了与结果集有关所有信息 // 此结果有几列组成,每列的列名,每列的数据类型 ResultSetMetaData rsmd = rs.getMetaData(); // 得到结果集列数 int columnCount = rsmd.getColumnCount(); // 输出此结果集的所有列名 for (int i = 1; i <= columnCount; i++) { System.out.print(rsmd.getColumnName(i) + "\t"); } System.out.println(""); // 遍历输出所有的数据 while (rs.next()) { // 如何在获取rs中的数据? for (int i = 1; i <= columnCount; i++) { String type = rsmd.getColumnTypeName(i); System.out.print(getResultSetValue(rs, i, type) + "\t"); } System.out.println(""); } } } catch (SQLException e) { e.printStackTrace(); } } // 从ResultSet中根据数据类型来得到数据值的方法 // 先处理常用的sqlserver的数据类型的对应 private String getResultSetValue(ResultSet rs, int index, String type) { String rstr = ""; try { if (rs != null && !"".equals(type) && index > 0) { if ("char".equals(type.trim()) || "varchar".equals(type.trim())) { if (rs.getString(index) != null) { rstr = rs.getString(index); } } else if ("int".equals(type.trim())) { rstr = rs.getInt(index) + ""; } else if ("decimal".equals(type.trim())) { rstr = String.valueOf(rs.getDouble(index)); } else if ("date".equals(type.trim())) { Date date = rs.getDate(index); if (date != null) { rstr = new SimpleDateFormat("yyyy年MM月dd日").format(date); } } else if ("timestamp".equals(type.trim()) || "datetime".equals(type.trim())) { Timestamp tt = rs.getTimestamp(index); if (tt != null) { rstr = new SimpleDateFormat("yyyy年MM月dd日 HH时mm分ss秒").format(tt); } } } } catch (SQLException e) { e.printStackTrace(); } return rstr; } /* //统一事务管理的批量sql的封装 public boolean iudSql(List<String> sqlList){ int ri = -1; if(stmt!=null){ try { ri = stmt.executeUpdate(sql); commit(); } catch (SQLException e) { e.printStackTrace(); rollBack(); } } return ri; }*/ // 关闭连接 public void close() { try { // 关闭所有的与数据库有关的对象 if (rs != null) { rs.close(); rs = null; } if (stmt != null) { stmt.close(); stmt = null; } if (pstmt != null) { pstmt.close(); pstmt = null; } if (cstmt != null) { cstmt.close(); cstmt = null; } if (connect != null) { connect.close(); connect = null; } } catch (SQLException e) { e.printStackTrace(); } } }

学Python后到底能干什么?网友:我太难了

感觉全世界营销文都在推Python,但是找不到工作的话,又有哪个机构会站出来给我推荐工作? 笔者冷静分析多方数据,想跟大家说:关于超越老牌霸主Java,过去几年间Python一直都被寄予厚望。但是事实是虽然上升趋势,但是国内环境下,一时间是无法马上就超越Java的,也可以换句话说:超越Java只是时间问题罢。 太嚣张了会Python的人!找工作拿高薪这么简单? https://edu....

大学四年自学走来,这些私藏的实用工具/学习网站我贡献出来了

大学四年,看课本是不可能一直看课本的了,对于学习,特别是自学,善于搜索网上的一些资源来辅助,还是非常有必要的,下面我就把这几年私藏的各种资源,网站贡献出来给你们。主要有:电子书搜索、实用工具、在线视频学习网站、非视频学习网站、软件下载、面试/求职必备网站。 注意:文中提到的所有资源,文末我都给你整理好了,你们只管拿去,如果觉得不错,转发、分享就是最大的支持了。 一、电子书搜索 对于大部分程序员...

在中国程序员是青春饭吗?

今年,我也32了 ,为了不给大家误导,咨询了猎头、圈内好友,以及年过35岁的几位老程序员……舍了老脸去揭人家伤疤……希望能给大家以帮助,记得帮我点赞哦。 目录: 你以为的人生 一次又一次的伤害 猎头界的真相 如何应对互联网行业的「中年危机」 一、你以为的人生 刚入行时,拿着傲人的工资,想着好好干,以为我们的人生是这样的: 等真到了那一天,你会发现,你的人生很可能是这样的: ...

Java校招入职华为,半年后我跑路了

何来 我,一个双非本科弟弟,有幸在 19 届的秋招中得到前东家华为(以下简称 hw)的赏识,当时秋招签订就业协议,说是入了某 java bg,之后一系列组织架构调整原因等等让人无法理解的神操作,最终毕业前夕,被通知调往其他 bg 做嵌入式开发(纯 C 语言)。 由于已至于校招末尾,之前拿到的其他 offer 又无法再收回,一时感到无力回天,只得默默接受。 毕业后,直接入职开始了嵌入式苦旅,由于从未...

Java基础知识面试题(2020最新版)

文章目录Java概述何为编程什么是Javajdk1.5之后的三大版本JVM、JRE和JDK的关系什么是跨平台性?原理是什么Java语言有哪些特点什么是字节码?采用字节码的最大好处是什么什么是Java程序的主类?应用程序和小程序的主类有何不同?Java应用程序与小程序之间有那些差别?Java和C++的区别Oracle JDK 和 OpenJDK 的对比基础语法数据类型Java有哪些数据类型switc...

@程序员:GitHub这个项目快薅羊毛

今天下午在朋友圈看到很多人都在发github的羊毛,一时没明白是怎么回事。 后来上百度搜索了一下,原来真有这回事,毕竟资源主义的羊毛不少啊,1000刀刷爆了朋友圈!不知道你们的朋友圈有没有看到类似的消息。 这到底是啥情况? 微软开发者平台GitHub 的一个区块链项目 Handshake ,搞了一个招募新会员的活动,面向GitHub 上前 25万名开发者派送 4,246.99 HNS币,大约价...

用python打开电脑摄像头,并把图像传回qq邮箱【Pyinstaller打包】

前言: 如何悄悄的打开朋友的摄像头,看看她最近过的怎么样,嘿嘿!这次让我带你们来实现这个功能。 注: 这个程序仅限在朋友之间开玩笑,别去搞什么违法的事情哦。 代码 发送邮件 使用python内置的email模块即可完成。导入相应的代码封装为一个send函数,顺便导入需要导入的包 注: 下面的代码有三处要修改的地方,两处写的qq邮箱地址,还有一处写的qq邮箱授权码,不知道qq邮箱授权码的可以去百度一...

做了5年运维,靠着这份监控知识体系,我从3K变成了40K

从来没讲过运维,因为我觉得运维这种东西不需要太多的知识面,然后我一个做了运维朋友告诉我大错特错,他就是从3K的运维一步步到40K的,甚至笑着说:我现在感觉自己什么都能做。 既然讲,就讲最重要的吧。 监控是整个运维乃至整个产品生命周期中最重要的一环,事前及时预警发现故障,事后提供详实的数据用于追查定位问题。目前业界有很多不错的开源产品可供选择。选择一款开源的监控系统,是一个省时省力、效率最高的方...

计算机网络——浅析网络层

一、前言 注意,关于ipv4和ipv6,ipv4是ip协议第4版本,也表示这个版本的ip一共4个字节,同样地,ipv6是ip协议第6版本,也表示这个版本的ip一共6个字节。 关于网络层使用路由器实现互联:在计算机网络的分层结构中,不同层有不同的中继设备: 计算机网络层 中继设备/中继系统 物理层 中继器、集线器Hub 数据链路层 网桥或交换机(交换机是多端口网桥,两者本质上是一个东西) 网络层 路...

我以为我学懂了数据结构,直到看了这个导图才发现,我错了

数据结构与算法思维导图

技术大佬:我去,你写的 switch 语句也太老土了吧

昨天早上通过远程的方式 review 了两名新来同事的代码,大部分代码都写得很漂亮,严谨的同时注释也很到位,这令我非常满意。但当我看到他们当中有一个人写的 switch 语句时,还是忍不住破口大骂:“我擦,小王,你丫写的 switch 语句也太老土了吧!” 来看看小王写的代码吧,看完不要骂我装逼啊。 private static String createPlayer(PlayerTypes p...

华为初面+综合面试(Java技术面)附上面试题

华为面试整体流程大致分为笔试,性格测试,面试,综合面试,回学校等结果。笔试来说,华为的难度较中等,选择题难度和网易腾讯差不多。最后的代码题,相比下来就简单很多,一共3道题目,前2题很容易就AC,题目已经记不太清楚,不过难度确实不大。最后一题最后提交的代码过了75%的样例,一直没有发现剩下的25%可能存在什么坑。 笔试部分太久远,我就不怎么回忆了。直接将面试。 面试 如果说腾讯的面试是挥金如土...

和黑客斗争的 6 天!

互联网公司工作,很难避免不和黑客们打交道,我呆过的两家互联网公司,几乎每月每天每分钟都有黑客在公司网站上扫描。有的是寻找 Sql 注入的缺口,有的是寻找线上服务器可能存在的漏洞,大部分都...

讲一个程序员如何副业月赚三万的真实故事

loonggg读完需要3分钟速读仅需 1 分钟大家好,我是你们的校长。我之前讲过,这年头,只要肯动脑,肯行动,程序员凭借自己的技术,赚钱的方式还是有很多种的。仅仅靠在公司出卖自己的劳动时...

win10暴力查看wifi密码

刚才邻居打了个电话说:喂小灰,你家wifi的密码是多少,我怎么连不上了。 我。。。 我也忘了哎,就找到了一个好办法,分享给大家: 第一种情况:已经连接上的wifi,怎么知道密码? 打开:控制面板\网络和 Internet\网络连接 然后右击wifi连接的无线网卡,选择状态 然后像下图一样: 第二种情况:前提是我不知道啊,但是我以前知道密码。 此时可以利用dos命令了 1、利用netsh wlan...

上班一个月,后悔当初着急入职的选择了

最近有个老铁,告诉我说,上班一个月,后悔当初着急入职现在公司了。他之前在美图做手机研发,今年美图那边今年也有一波组织优化调整,他是其中一个,在协商离职后,当时捉急找工作上班,因为有房贷供着,不能没有收入来源。所以匆忙选了一家公司,实际上是一个大型外包公司,主要派遣给其他手机厂商做外包项目。**当时承诺待遇还不错,所以就立马入职去上班了。但是后面入职后,发现薪酬待遇这块并不是HR所说那样,那个HR自...

女程序员,为什么比男程序员少???

昨天看到一档综艺节目,讨论了两个话题:(1)中国学生的数学成绩,平均下来看,会比国外好?为什么?(2)男生的数学成绩,平均下来看,会比女生好?为什么?同时,我又联想到了一个技术圈经常讨...

副业收入是我做程序媛的3倍,工作外的B面人生是怎样的?

提到“程序员”,多数人脑海里首先想到的大约是:为人木讷、薪水超高、工作枯燥…… 然而,当离开工作岗位,撕去层层标签,脱下“程序员”这身外套,有的人生动又有趣,马上展现出了完全不同的A/B面人生! 不论是简单的爱好,还是正经的副业,他们都干得同样出色。偶尔,还能和程序员的特质结合,产生奇妙的“化学反应”。 @Charlotte:平日素颜示人,周末美妆博主 大家都以为程序媛也个个不修边幅,但我们也许...

MySQL数据库面试题(2020最新版)

文章目录数据库基础知识为什么要使用数据库什么是SQL?什么是MySQL?数据库三大范式是什么mysql有关权限的表都有哪几个MySQL的binlog有有几种录入格式?分别有什么区别?数据类型mysql有哪些数据类型引擎MySQL存储引擎MyISAM与InnoDB区别MyISAM索引与InnoDB索引的区别?InnoDB引擎的4大特性存储引擎选择索引什么是索引?索引有哪些优缺点?索引使用场景(重点)...

记一次腾讯面试,我挂在了最熟悉不过的队列上……

腾讯后台面试,面试官问:如何自己实现队列?

如果你是老板,你会不会踢了这样的员工?

有个好朋友ZS,是技术总监,昨天问我:“有一个老下属,跟了我很多年,做事勤勤恳恳,主动性也很好。但随着公司的发展,他的进步速度,跟不上团队的步伐了,有点...

离职半年了,老东家又发 offer,回不回?

有小伙伴问松哥这个问题,他在上海某公司,在离职了几个月后,前公司的领导联系到他,希望他能够返聘回去,他很纠结要不要回去? 俗话说好马不吃回头草,但是这个小伙伴既然感到纠结了,我觉得至少说明了两个问题:1.曾经的公司还不错;2.现在的日子也不是很如意。否则应该就不会纠结了。 老实说,松哥之前也有过类似的经历,今天就来和小伙伴们聊聊回头草到底吃不吃。 首先一个基本观点,就是离职了也没必要和老东家弄的苦...

2020阿里全球数学大赛:3万名高手、4道题、2天2夜未交卷

阿里巴巴全球数学竞赛( Alibaba Global Mathematics Competition)由马云发起,由中国科学技术协会、阿里巴巴基金会、阿里巴巴达摩院共同举办。大赛不设报名门槛,全世界爱好数学的人都可参与,不论是否出身数学专业、是否投身数学研究。 2020年阿里巴巴达摩院邀请北京大学、剑桥大学、浙江大学等高校的顶尖数学教师组建了出题组。中科院院士、美国艺术与科学院院士、北京国际数学...

HTTP与HTTPS的区别

面试官问HTTP与HTTPS的区别,我这样回答让他竖起大拇指!

男生更看重女生的身材脸蛋,还是思想?

往往,我们看不进去大段大段的逻辑。深刻的哲理,往往短而精悍,一阵见血。问:产品经理挺漂亮的,有点心动,但不知道合不合得来。男生更看重女生的身材脸蛋,还是...

程序员为什么千万不要瞎努力?

本文作者用对比非常鲜明的两个开发团队的故事,讲解了敏捷开发之道 —— 如果你的团队缺乏统一标准的环境,那么即使勤劳努力,不仅会极其耗时而且成果甚微,使用...

为什么程序员做外包会被瞧不起?

二哥,有个事想询问下您的意见,您觉得应届生值得去外包吗?公司虽然挺大的,中xx,但待遇感觉挺低,马上要报到,挺纠结的。

当HR压你价,说你只值7K,你该怎么回答?

当HR压你价,说你只值7K时,你可以流畅地回答,记住,是流畅,不能犹豫。 礼貌地说:“7K是吗?了解了。嗯~其实我对贵司的面试官印象很好。只不过,现在我的手头上已经有一份11K的offer。来面试,主要也是自己对贵司挺有兴趣的,所以过来看看……”(未完) 这段话主要是陪HR互诈的同时,从公司兴趣,公司职员印象上,都给予对方正面的肯定,既能提升HR的好感度,又能让谈判气氛融洽,为后面的发挥留足空间。...

面试:第十六章:Java中级开发(16k)

HashMap底层实现原理,红黑树,B+树,B树的结构原理 Spring的AOP和IOC是什么?它们常见的使用场景有哪些?Spring事务,事务的属性,传播行为,数据库隔离级别 Spring和SpringMVC,MyBatis以及SpringBoot的注解分别有哪些?SpringMVC的工作原理,SpringBoot框架的优点,MyBatis框架的优点 SpringCould组件有哪些,他们...

面试阿里p7,被按在地上摩擦,鬼知道我经历了什么?

面试阿里p7被问到的问题(当时我只知道第一个):@Conditional是做什么的?@Conditional多个条件是什么逻辑关系?条件判断在什么时候执...

立即提问
相关内容推荐